初始化设备是应用程序在渲染场景之前必须完成的首要任务之一。
创建设备和实时上下文
- 填充DXGI_SWAP_CHAIN_DESC结构体的缓冲区数据格式和大小信息。想要知道更多的信息,参考如何:创建交换链。下面的代码演示怎么去填充DXGI_SWAP_CHAIN_DESC结构体。
DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = 640; sd.BufferDesc.Height = 480; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE;
- 使用步骤1中填充的DXGI_SWAP_CHAIN_DESC结构体,通过调用D3D11CreateDeviceAndSwapChain函数同时初始化一个设备和交换链。
D3D_FEATURE_LEVEL FeatureLevelsRequested = D3D_FEATURE_LEVEL_11_0; UINT numLevelsRequested = 1; D3D_FEATURE_LEVEL FeatureLevelsSupported; if( FAILED (hr = D3D11CreateDeviceAndSwapChain( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &FeatureLevelsRequested, numFeatureLevelsRequested, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &FeatureLevelsSupported, &g_pImmediateContext ))) { return hr; }
- 通过调用ID3D11Device::CreateRenderTargetView函数创建一个渲染目标视图,并通过调用ID3D11DeviceContext::OMSetRenderTargets函数绑定一个后备缓冲区作为渲染目标。
ID3D11Texture2D* pBackBuffer; // Get a pointer to the back buffer hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); // Create a render-target view g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView ); // Bind the view g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, NULL );
- 通过定义一个ViewPort对象来确定渲染目标的哪一部分可以显示。使用D3D11_VIEWPORT结构体来定义ViewPort对象,并通过ID3D11DeviceContext::RSSetViewports函数设置到设备上下文中。
// Setup the viewport D3D11_VIEWPORT vp; vp.Width = 640; vp.Height = 480; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; g_pImmediateContext->RSSetViewports( 1, &vp );