DirectX入门之初始化Direct3D及常见问题

这篇文章主要讲解如何初始化Direct3D。Direct3D初始化成功后,我们将的到一个代表显卡的C++对象(类型:IDrect3DDevice9)。

初始化流程图:

DirectX入门之初始化Direct3D及常见问题_第1张图片

完整代码:


   //全局变量
   IDirect3DDevice9 *device = 0 ;
   // Step 1: Create the IDirect3D9 object.

   IDirect3D9* d3d9 = 0;
   d3d9 = Direct3DCreate9(D3D_SDK_VERSION);

   if (!d3d9)
   {
       return false;
   }

   // Step 2: Check for hardware vp.

   D3DCAPS9 caps;
   d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps);

   int vp = 0;
   if (caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
       vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
   else
       vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;

   // Step 3: Fill out the D3DPRESENT_PARAMETERS structure.

   D3DPRESENT_PARAMETERS d3dpp;
   d3dpp.BackBufferWidth = 800;
   d3dpp.BackBufferHeight = 600;
   d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
   d3dpp.BackBufferCount = 1;
   d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
   d3dpp.MultiSampleQuality = 0;
   d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
   d3dpp.hDeviceWindow = hWnd;
   d3dpp.Windowed = false;
   d3dpp.EnableAutoDepthStencil = true;
   d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
   d3dpp.Flags = 0;
   d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
   d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    ///////////////////////////////
    // Step 4: Create the device.(device代表的是物理显卡)
    //////////////////////////////
       HRESULT hr = d3d9->CreateDevice(
       D3DADAPTER_DEFAULT, // primary adapter
       D3DDEVTYPE_HAL,         // device type
       hWnd,               // window associated with device
       vp,                 // vertex processing
       &d3dpp,             // present parameters
       &device);            // return created device

       if (FAILED(hr))
       {
           d3d9->Release(); // done with d3d9 object
           return false;
       }
       else {
           ::MessageBox(0, L"显卡对象创建成功",0,0);
       }
   }

   d3d9->Release(); // done with d3d9 object

可能会遇到的错误:

错误类型:

无法解析的外部符号 Direct3DCreate9@4

这里写图片描述
解决方案一:
在VS.NET中的项目/属性/配置属性/连接器/输入/附加依赖项中添加以下文件名,d3dx9.lib d3dxof.lib d3d9.lib winmm.lib dxguid.lib comctl32.lib 就可以了.
解决方案二:

    #pragma comment(lib,"d3d9.lib") 
    #pragma comment(lib,"winmm.lib") 
    #pragma comment(lib,"d3dx9.lib")

你可能感兴趣的:(DirectX快速入门)