Direct3D 프로그램 설계 기초(2)

8864 단어
Direct3D 프로그램 설계 기초(2)
창 만들기
Direct3D는 Microsoft Windows를 기반으로 하는 그래픽 개발 인터페이스로 Windows 창을 기반으로 해야 하기 때문에 창을 만들어야 하고 창을 만들려면 먼저 창 클래스를 등록해야 한다.예제 프로그램에서 창 클래스를 등록하고 창 클래스에 따라 창을 만드는 코드는 다음과 같습니다.
	WNDCLASSEX wc;
	wc.cbSize			= sizeof(WNDCLASSEX);
wc.style = CS_CLASSDC;
wc.lpfnWndProc = WinProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = inst;
wc.hIcon = NULL;
wc.hCursor = NULL;
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = CLASS_NAME;
wc.hIconSm = NULL;
	if(! RegisterClassEx(&wc))
return -1;
	HWND hwnd = CreateWindow(CLASS_NAME, "Direct3D App", WS_OVERLAPPEDWINDOW, 200, 100, 600, 500,
NULL, NULL, wc.hInstance, NULL);
	if(hwnd == NULL)
return -1;

 
Direct3D 초기화
도면을 그릴 수 있는 창을 만든 후 Direct3D를 사용하여 도면을 렌더링하기 전에 Direct3D 객체를 만들고 인터페이스 포인터를 가져와 Direct3D 객체를 통해 Direct3D 장치 객체를 작성하는 등 Direct3D와 관련된 초기화 작업이 필요합니다.
bool init_d3d(HWND hwnd)
{
g_d3d = Direct3DCreate9(D3D_SDK_VERSION);
	if(g_d3d == NULL)
return false;
	D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
	d3dpp.Windowed			= TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
	if(FAILED(g_d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp, &g_device)))
{
return false;
}
	return true;
}

Direct3D 장비(Direct3D Device)는 Direct3D의 모든 드로잉 작업을 정의하며 대부분의 Direct3D 작업은 Direct3D 장치 인터페이스를 통해 수행됩니다.비교해 보면 Direct3D 대상은 DirectX가 정보를 표시하는 설명과 같고 Direct3D 장치 대상은 3D 기능의 구체적인 실현이다.
Direct3D 장치를 만들려면 IDirect3D9::CreateDevice() 함수를 호출합니다.
Creates a device to represent the display adapter.
HRESULT CreateDevice(
UINT Adapter,
D3DDEVTYPE DeviceType,
HWND hFocusWindow,
DWORD BehaviorFlags,
D3DPRESENT_PARAMETERS * pPresentationParameters,
IDirect3DDevice9 ** ppReturnedDeviceInterface
);

Parameters
Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.
hFocusWindow
[in] The focus window alerts Direct3D when an application switches from foreground mode to background mode. See Remarks.
  • For full-screen mode, the window specified must be a top-level window.
  • For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.

  • BehaviorFlags
    [in] Combination of one or more options that control device creation. For more information, see D3DCREATE.
    pPresentationParameters
    Pointer to a D3DPRESENT_PARAMETERS structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies D3DCREATE_ADAPTERGROUP_DEVICE, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created.
    [in, out] For Windows 2000 and Windows XP, the full-screen device display refresh rate is set in the following order:
  • User-specified nonzero ForcedRefreshRate registry key, if supported by the device.
  • Application-specified nonzero refresh rate value in the presentation parameter.
  • Refresh rate of the latest desktop mode, if supported by the device.
  • 75 hertz if supported by the device.
  • 60 hertz if supported by the device.
  • Device default.

  • An unsupported refresh rate will default to the closest supported refresh rate below it. For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz.
    pPresentationParameters is both an input and an output parameter. Calling this method may change several members including:
  • If BackBufferCount, BackBufferWidth, and BackBufferHeight are 0 before the method is called, they will be changed when the method returns.
  • If BackBufferFormat equals D3DFMT_UNKNOWN before the method is called, it will be changed when the method returns.

  •  
    ppReturnedDeviceInterface
    [out, retval] Address of a pointer to the returned IDirect3DDevice9 interface, which represents the created 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: D3DERR_DEVICELOST, D3DERR_INVALIDCALL, D3DERR_NOTAVAILABLE, D3DERR_OUTOFVIDEOMEMORY.
    Remarks
    This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in D3DPRESENT_PARAMETERS).
    When you create a Direct3D device, you supply two different window parameters: a focus window (hFocusWindow) and a device window (the hDeviceWindow in D3DPRESENT_PARAMETERS). The purpose of each window is:
  • The focus window alerts Direct3D when an application switches from foreground mode to background mode (via Alt-Tab, a mouse click, or some other method). A single focus window is shared by each device created by an application.
  • The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during IDirect3DDevice9::Present.

  • This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE. Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window.
    Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and at least one of these vertex processing flags must be specified when calling this method.
    Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.)
    The methods IDirect3DDevice9::Reset, IUnknown, and IDirect3DDevice9::TestCooperativeLevel must be called from the same thread that used this method to create a device.
    D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset, and IDirect3DDevice9::CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling IDirect3D9::CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified.
    If you attempt to create a device on a 0x0 sized window, IDirect3D9::CreateDevice will fail.
     
    메시지 순환
    Direct3D에서 렌더링된 도면은 일반적으로 메시지 주기에서 수행됩니다.
    		MSG msg;
    ZeroMemory(&msg, sizeof(msg));
    		while(msg.message != WM_QUIT)
    {
    if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    }
    else
    {
    render();
    }
    }

    이 코드의 주요 부분은 PeekMessage(), TranslateMessage(), DispatchMessage()로 구성되며 Windows 프로그램의 표준적인 메시지 순환 처리 코드이다.프로그램 메시지 대기열에 메시지가 나타나면 PeekMessage () 는 브리 값 TRUE를 되돌려주고 TranslateMessage () 를 실행하여 메시지 변환을 한 다음 DispatchMessage () 로 메시지를 창 프로세스 함수에 전달합니다.
    특히 메시지 루프에 GetMessage() 함수가 아닌 PeekMessage() 함수를 사용하는 점에 유의해야 합니다.함수 PeekMessage()와 GetMessage()는 기능이 대체적으로 같고, 메시지 대기열에서 메시지를 하나 꺼내는 역할을 하는데, 유일하게 다른 것은 GetMessage()가 메시지 대기열에 메시지가 없는 것을 발견할 때마다 출입문이 닫히고 PeekMessage()가 메시지 대기열에 메시지가 없는 것을 발견하면 시스템 제어권을 되찾아 프로그램이 여기에 일정 시간 머무르게 하는 것이다. 응용 프로그램은 바로 이때 Render() 함수를 처리한다.즉, 렌더링 함수render () 는 프로그램이 실행될 때의 빈 시간에 호출된다는 것이다.
    PeekMessage()와 GetMessage()의 운영 메커니즘의 차이를 이해하는 것은 Direct3D 프로그램에서 애니메이션을 어떻게 실현하는지 이해하는 데 매우 관건적이다.

    좋은 웹페이지 즐겨찾기