Directx3D9学习之一:环境搭建与运行第一个程序环境配置(基于VS2012与win7)

Directx3D9学习之一:环境搭建与运行第一个程序环境配置(基于VS2012与win7)
作者:lhqsine
一、搭建《DIRECTX.9.0.3D游戏开发编程基础》开发环境与第一个程序

1、下载directX库

vs2012以后的版本都集成了基本的directx库,所以如果不需要用到directx3D的扩展库(例如d3dx8~11.lib),则可以直接使用。但是龙书中则用到了d3dx9.lib库,因此还是需要下载微软的DirectX Software Development Kit,下载地址:http://www.microsoft.com/en-us/download/details.aspx?id=6812。

2、安装directX

直接安装即可,假如你先安装了vs2012,则安装到最后会有个报错,这个是由于微软单独的directx到2010_jun_10就没有了再更新,之后安装会检测你的vs版本,如果较新则会报错,其实这个错误不影响后续使用,想避免报错,有个笨方法就是先卸载vs,然后先安装directx3D,之后再安装vs。

3、第一个程序

//
// 
// File: d3dUtility.h
// 
// Author: Frank Luna (C) All Rights Reserved
//
// System: AMD Athlon 1800+ XP, 512 DDR, Geforce 3, Windows XP, MSVC++ 7.0 
//
// Desc: Provides utility functions for simplifying common tasks.
//          
//

#ifndef __d3dUtilityH__
#define __d3dUtilityH__

#include <d3dx9.h>
#include <string>

namespace d3d
{
	bool InitD3D(
		HINSTANCE hInstance,       // [in] Application instance.
		int width, int height,     // [in] Backbuffer dimensions.
		bool windowed,             // [in] Windowed (true)or full screen (false).
		D3DDEVTYPE deviceType,     // [in] HAL or REF
		IDirect3DDevice9** device);// [out]The created device.

	int EnterMsgLoop( 
		bool (*ptr_display)(float timeDelta));

	LRESULT CALLBACK WndProc(
		HWND hwnd,
		UINT msg, 
		WPARAM wParam,
		LPARAM lParam);

	template<class T> void Release(T t)
	{
		if( t )
		{
			t->Release();
			t = 0;
		}
	}
		
	template<class T> void Delete(T t)
	{
		if( t )
		{
			delete t;
			t = 0;
		}
	}
}

#endif // __d3dUtilityH__

//
// 
// File: d3dUtility.cpp
// 
// Author: Frank Luna (C) All Rights Reserved
//
// System: AMD Athlon 1800+ XP, 512 DDR, Geforce 3, Windows XP, MSVC++ 7.0 
//
// Desc: Provides utility functions for simplifying common tasks.
//          
//

#include "d3dUtility.h"

bool d3d::InitD3D(
	HINSTANCE hInstance,
	int width, int height,
	bool windowed,
	D3DDEVTYPE deviceType,
	IDirect3DDevice9** device)
{
	//
	// Create the main application window.
	//

	WNDCLASS wc;

	wc.style         = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc   = (WNDPROC)d3d::WndProc; 
	wc.cbClsExtra    = 0;
	wc.cbWndExtra    = 0;
	wc.hInstance     = hInstance;
	wc.hIcon         = LoadIcon(0, IDI_APPLICATION);
	wc.hCursor       = LoadCursor(0, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName  = 0;
	wc.lpszClassName = "Direct3D9App";

	if( !RegisterClass(&wc) ) 
	{
		::MessageBox(0, "RegisterClass() - FAILED", 0, 0);
		return false;
	}
		
	HWND hwnd = 0;
	hwnd = ::CreateWindow("Direct3D9App", "Direct3D9App", 
		WS_EX_TOPMOST,
		0, 0, width, height,
		0 /*parent hwnd*/, 0 /* menu */, hInstance, 0 /*extra*/); 

	if( !hwnd )
	{
		::MessageBox(0, "CreateWindow() - FAILED", 0, 0);
		return false;
	}

	::ShowWindow(hwnd, SW_SHOW);
	::UpdateWindow(hwnd);

	//
	// Init D3D: 
	//

	HRESULT hr = 0;

	// Step 1: Create the IDirect3D9 object.

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

    if( !d3d9 )
	{
		::MessageBox(0, "Direct3DCreate9() - FAILED", 0, 0);
		return false;
	}

	// Step 2: Check for hardware vp.

	D3DCAPS9 caps;
	d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, deviceType, &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            = width;
	d3dpp.BackBufferHeight           = height;
	d3dpp.BackBufferFormat           = D3DFMT_A8R8G8B8;
	d3dpp.BackBufferCount            = 1;
	d3dpp.MultiSampleType            = D3DMULTISAMPLE_NONE;
	d3dpp.MultiSampleQuality         = 0;
	d3dpp.SwapEffect                 = D3DSWAPEFFECT_DISCARD; 
	d3dpp.hDeviceWindow              = hwnd;
	d3dpp.Windowed                   = windowed;
	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.

	hr = d3d9->CreateDevice(
		D3DADAPTER_DEFAULT, // primary adapter
		deviceType,         // device type
		hwnd,               // window associated with device
		vp,                 // vertex processing
	    &d3dpp,             // present parameters
	    device);            // return created device

	if( FAILED(hr) )
	{
		// try again using a 16-bit depth buffer
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		
		hr = d3d9->CreateDevice(
			D3DADAPTER_DEFAULT,
			deviceType,
			hwnd,
			vp,
			&d3dpp,
			device);

		if( FAILED(hr) )
		{
			d3d9->Release(); // done with d3d9 object
			::MessageBox(0, "CreateDevice() - FAILED", 0, 0);
			return false;
		}
	}

	d3d9->Release(); // done with d3d9 object
	
	return true;
}

int d3d::EnterMsgLoop( bool (*ptr_display)(float timeDelta) )
{
	MSG msg;
	::ZeroMemory(&msg, sizeof(MSG));

	static float lastTime = (float)timeGetTime(); 

	while(msg.message != WM_QUIT)
	{
		if(::PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			::TranslateMessage(&msg);
			::DispatchMessage(&msg);
		}
		else
        {	
			float currTime  = (float)timeGetTime();
			float timeDelta = (currTime - lastTime)*0.001f;

			ptr_display(timeDelta);

			lastTime = currTime;
        }
    }
    return msg.wParam;
}



//
// 
// File: d3dinit.cpp
// 
// Author: Frank Luna (C) All Rights Reserved
//
// System: AMD Athlon 1800+ XP, 512 DDR, Geforce 3, Windows XP, MSVC++ 7.0 
//
// Desc: Demonstrates how to initialize Direct3D, how to use the book's framework
//       functions, and how to clear the screen to black.  Note that the Direct3D
//       initialization code is in the d3dUtility.h/.cpp files.
//          
//

#include "d3dUtility.h"

//
// Globals
//

IDirect3DDevice9* Device = 0; 

//
// Framework Functions
//

bool Setup()
{
	// Nothing to setup in this sample.

	return true;
}

void Cleanup()
{
	// Nothing to cleanup in this sample.
}

bool Display(float timeDelta)
{
	if( Device ) // Only use Device methods if we have a valid device.
	{
		// Instruct the device to set each pixel on the back buffer black -
		// D3DCLEAR_TARGET: 0x00000000 (black) - and to set each pixel on
		// the depth buffer to a value of 1.0 - D3DCLEAR_ZBUFFER: 1.0f.
		Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 1.0f, 0);

		// Swap the back and front buffers.
		Device->Present(0, 0, 0, 0);
	}
	return true;
}

//
// WndProc
//
LRESULT CALLBACK d3d::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch( msg )
	{
	case WM_DESTROY:
		::PostQuitMessage(0);
		break;
		
	case WM_KEYDOWN:
		if( wParam == VK_ESCAPE )
			::DestroyWindow(hwnd);
		break;
	}
	return ::DefWindowProc(hwnd, msg, wParam, lParam);
}

//
// WinMain
//
int WINAPI WinMain(HINSTANCE hinstance,
				   HINSTANCE prevInstance, 
				   PSTR cmdLine,
				   int showCmd)
{
	if(!d3d::InitD3D(hinstance,
		640, 480, true, D3DDEVTYPE_HAL, &Device))
	{
		::MessageBox(0, "InitD3D() - FAILED", 0, 0);
		return 0;
	}
		
	if(!Setup())
	{
		::MessageBox(0, "Setup() - FAILED", 0, 0);
		return 0;
	}

	d3d::EnterMsgLoop( Display );

	Cleanup();

	Device->Release();

	return 0;
}

4、让程序可运行

配置库与头文件路径:

右键工程项目,选择属性->配置属性->VC++目录,修改包含目录与库目录。如图所示,点击编辑选择到你所安装的目录例如我的库是:E:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86,包含目录则是在Include中。


这个配置完后,如果程序还是不能运行,则需要通过链接器直接指定要链接的库了。

还是右键工程项目,选择属性->配置属性->连接器->输入->附加依赖项,输入如下:


最后大功告成结果:


二、简单暴力第一个Directx3D程序

其实如果不使用dirctX3D的扩展库,直接使用VS2012的基本directX3D也可以直接写个最简单的DirectX3D程序,代码如下,

第一种:直接使用代码设置链

主要使用了一些设置链,以下代码相当于设置了指定链:

#pragma comment(lib, "d3d9.lib")  
#pragma comment(lib, "ddraw.lib")

#ifndef UNICODE
#define UNICODE
#endif


#include <d3d9.h>
#include <ddraw.h>  
#pragma comment(lib, "d3d9.lib")  
#pragma comment(lib, "ddraw.lib")


 //--------------------------------------------
 //全局变量
 //--------------------------------------------
 LPDIRECT3D9 g_pD3D =NULL;//Direct3D对象
 //g_pD3D是Direct3D接口指针
 LPDIRECT3DDEVICE9 g_pd3dDevice=NULL;//Direct3D设备对象
 
 //--------------------------------------------
 //Desc:初始化Direct3D
 //--------------------------------------------
 
 HRESULT InitD3D(HWND hWnd)
  {
 //创建Direct3D对象,该对象用来创建Direct3D设备对象
  if(NULL==(g_pD3D=Direct3DCreate9(D3D_SDK_VERSION)))
   return E_FAIL;
  //设置D3DPRESENT_PARAMETERS结构,准备创建Direct3D设备对象)
  D3DPRESENT_PARAMETERS d3dpp;//创建Direct3D设备对象参数d3dpp
  ZeroMemory(&d3dpp,sizeof(d3dpp));
  d3dpp.Windowed =TRUE;//窗口还是全屏幕
     d3dpp.SwapEffect=D3DSWAPEFFECT_DISCARD;//后台缓存复制到前台后,清除后台缓存
  d3dpp.BackBufferFormat =D3DFMT_UNKNOWN;//后台缓存格式和前台缓存格式相同
 
  //创建Direct3D设备对象
  if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL ,hWnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&g_pd3dDevice)))
     //参数说明,按顺序:Adapter指定显卡序号,默认显卡,指定设备类型(HAL,硬件抽象层设备),窗口指针,软件运算方式)
   {
   return E_FAIL;
  }
    return S_OK;
 }
 
 //----------------------------------------------
 //Desc:释放创建对象
 //----------------------------------------------
 VOID Cleanup()
  {
 //释放Direct3D设备对象
  if (g_pd3dDevice!=NULL)
   g_pd3dDevice->Release();//对应COM计数器会减1
  //释放Direct3D对象
  if (g_pD3D!=NULL)
   g_pD3D->Release();//对应COM计数器会减1
 }
 
 //----------------------------------------------
 //Desc:渲染图形
 //----------------------------------------------
 VOID Render()
  {
 //清空后台缓冲
 g_pd3dDevice->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(255,0,0),1.0f,0);
 //矩形数量;要清空的矩形区域,若值为NULL,则第一个参数为0;清空的内容:颜色缓冲区;清空颜色缓冲区后颜色缓冲区的值;颜色深度;模板值
 if (SUCCEEDED(g_pd3dDevice->BeginScene()))
     {
     //在后台缓冲区绘制图形
     //结束在后台缓冲区绘制图形
     g_pd3dDevice->EndScene();
    }
 //将在后台缓冲区绘制的图形提交到前台缓冲区显示
 g_pd3dDevice->Present(NULL,NULL,NULL,NULL);
 //参数说明:复制源的矩形区域指针;复制目标的矩形区域指针;当前窗口指针;最小更新区域指针
 }
 
 
 //-----------------------------------------------
 //Desc:消息处理
 //-----------------------------------------------
 LRESULT WINAPI MsgProc(HWND hWnd,UINT msg, WPARAM wParam, LPARAM lParam)
  {
 switch(msg)
     {
     case WM_DESTROY:
      Cleanup();
      PostQuitMessage(0);
      return 0;
     case WM_PAINT:
      Render();
      ValidateRect(hWnd,NULL);
      return 0;
    }
 return DefWindowProc(hWnd,msg,wParam,lParam);
 }
 
 
 //-----------------------------------------------
 //Desc:程序入口
 //-----------------------------------------------
 
 INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, INT)
  {
 //注册窗口类
  WNDCLASSEX wc={sizeof(WNDCLASSEX),CS_CLASSDC, MsgProc,0L,0L,GetModuleHandle(NULL),NULL,NULL,NULL,NULL,L"ClassName",NULL};
 RegisterClassEx( &wc);
 //创建窗口
 HWND hWnd=CreateWindow(L"ClassName",L"最简单的Direct3D程序",WS_OVERLAPPEDWINDOW,0,0,1024,768,NULL,NULL,wc.hInstance,NULL);
 
 //初始化Direct3D
 if (SUCCEEDED(InitD3D(hWnd)))
  {
  //显示主窗口
  ShowWindow(hWnd,SW_SHOWDEFAULT);
  UpdateWindow(hWnd);
 
  //进入消息循环
  MSG msg;
  ZeroMemory(&msg,sizeof(msg));
  while(msg.message!=WM_QUIT)
   {
   if(PeekMessage(&msg,NULL,0U,0U,PM_REMOVE))//PeekMessage和GetMessage的区别
    //PeekMessage过程中用来处理Render而GetMessage过门不入,不会抢系统控制权
    {
    TranslateMessage(&msg);//消息转换
    DispatchMessage(&msg);//消息传递给窗口过程函数
   }
   else
    {
    Render();//渲染图形,渲染函数一般都是在程序空闲时调用的
   }
  }
 }
 UnregisterClass(L"ClassName",wc.hInstance);//参数作用:要注销的类名字符串指针;应用程序句柄
 return 0;
 }

第二种:连接器中设置

其实也可以直接还是右键工程项目,选择属性->配置属性->连接器->输入->附加依赖项,输入:

d3d9.lib




“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 2

打赏作者

望月咸鱼

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值