Directx 纹理贴图 模仿地面效果

#include <d3dx9.h>
#include <string>
#include <tchar.h>
#pragma warning(disable: 4996)
#include <strsafe.h>
#pragma warning(disable: 4996)

//////////////////////////////////////////////////////////////////////////
#define SAFE_RELEASE(p) { if(p) { p->Release(); (p) = NULL; } }
#define SAFE_DELETE(p)  { if(p) { delete(p); (p) = NULL; } }

IDirect3DDevice9 *Device = 0;

ID3DXFont *Font = 0;
wchar_t strFPS[30];
float FPS = 0.0f;
RECT ClientRect;

LPDIRECT3DTEXTURE9 pTexture;

IDirect3DVertexBuffer9 *VB = 0;

D3DXMATRIX World;

float Get_FPS();

///////////////////////////////////////////////////////////////////////////////
struct ColorVertex
{
	ColorVertex(){}

	ColorVertex(float x, float y, float z, float u, float v)
	{
		_x = x;	 _y = y;  _z = z; _u = u; _v = v;
	}

	float _x, _y, _z, _u, _v;

	static const DWORD FVF;
};
const DWORD ColorVertex::FVF = D3DFVF_XYZ | D3DFVF_TEX1;


//////////////////////////////////////////////////////////////////////////                   
bool Setup()
{
	Device->CreateVertexBuffer(4*sizeof(ColorVertex), D3DUSAGE_WRITEONLY,
		ColorVertex::FVF, D3DPOOL_DEFAULT, &VB, 0);

	ColorVertex *vertexs;
	VB->Lock(0, 0, (void**)&vertexs, 0);

	vertexs[0] = ColorVertex(-4.0f, -4.0f, -4.0f, 0.0f, 0.0f);
	vertexs[1] = ColorVertex(-4.0f, -4.0f,  4.0f, 0.0f, 1.0f);
	vertexs[2] = ColorVertex( 4.0f, -4.0f, -4.0f, 1.0f, 0.0f);
	vertexs[3] = ColorVertex( 4.0f, -4.0f,  4.0f, 1.0f, 1.0f);

	VB->Unlock();


	//////////////////////////////////////////////////////////////////////////
	D3DXCreateFont(Device,20,10,0,D3DX_DEFAULT,false,DEFAULT_CHARSET,
		0,DEFAULT_QUALITY,0,TEXT("Times New Roman"),&Font);

	D3DXCreateTextureFromFile(Device,TEXT("ground.jpg"),&pTexture);

	//////////////////////////////////////////////////////////////////////////
	D3DXVECTOR3 postion(0.0f, 3.0f, -5.0f);
	D3DXVECTOR3 targer(0.0f, 0.0f, 0.0f);
	D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
	D3DXMATRIX V;
	D3DXMatrixLookAtLH(&V, &postion, &targer, &up);

	Device->SetTransform(D3DTS_VIEW, &V);

	//////////////////////////////////////////////////////////////////////////
	D3DXMATRIX proj;
	D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI * 0.5f, float(640)/float(480),
		 1.0f, 1000.0f);
	Device->SetTransform(D3DTS_PROJECTION, &proj);

	Device->SetRenderState(D3DRS_LIGHTING, false);

	return true;
}

void Clearup()
{
	SAFE_RELEASE(VB);
}



///////////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
	switch (msg)
	{
		case WM_PAINT:
			ValidateRect(hwnd,NULL);
		break;

		case WM_DESTROY:
			Clearup();
			PostQuitMessage(0);
			break;

		case WM_KEYDOWN:
			if(wParam == VK_ESCAPE)
				DestroyWindow(hwnd);
			break;
	}

	return DefWindowProc(hwnd,msg,wParam,lParam);
}


 bool Display()
 {
	 if(Device)
	 {
		 Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
			 D3DCOLOR_XRGB(40, 40, 40), 1.0f, 0);
		 Device->BeginScene();

		 //让四边形顺时针绕Y轴匀速转动
		 /* D3DXMATRIX worldMatrix;
		 UINT iTime = timeGetTime() % 1000;
		 float fAngle = iTime * ( D3DX_PI * 2 ) / 1000.0f;
		 D3DXMatrixRotationY(&worldMatrix, fAngle);
		 Device->SetTransform(D3DTS_WORLD, &worldMatrix);*/

	     //////////////////////////////////////////////////////////////////////////
		 Device->SetFVF(ColorVertex::FVF);

		 Device->SetTexture(0,pTexture);

		 Device->SetStreamSource(0, VB, 0, sizeof(ColorVertex));
		
		 Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);

		 Device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
		 Device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
		
		 RECT ClientRect = {20, 20, 190, 100};
		 int charCount = swprintf_s(strFPS,20,TEXT("FPS:%f"),Get_FPS());
		 Font->DrawText(NULL,strFPS,charCount,&ClientRect,DT_BOTTOM | DT_RIGHT, D3DCOLOR_XRGB(0,240,50));

		 Device->EndScene();
	 	 Device->Present(0, 0, 0, 0);
	 }

	 return true;
 }



int EnterMsgLoop(bool (*ptr_display)())
{
	MSG msg;
	ZeroMemory(&msg,sizeof(MSG));

	while (msg.message != WM_QUIT)
	{
		if(PeekMessage(&msg, 0, 0, 0,PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			ptr_display();
		}
	}

	return msg.wParam;
}



///////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
				   LPSTR lpCmdLine, int nShowCmd )
{
	WNDCLASSEX wc;

	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.cbClsExtra = 0;
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.cbWndExtra = 0;
	wc.hbrBackground = HBRUSH(GetStockObject(WHITE_BRUSH));
	wc.hCursor = LoadCursor(0,IDC_ARROW);
	wc.hInstance = hInstance;
	//wc.hIcon = LoadIcon(0,IDI_APPLICATION);
	wc.hIcon = (HICON)::LoadImage(NULL,TEXT("icon.ico"),IMAGE_ICON,0,0,LR_DEFAULTSIZE | LR_LOADFROMFILE);
	//wc.hIconSm = LoadIcon(0,IDI_APPLICATION);
	wc.hIconSm = (HICON)::LoadImage(NULL,TEXT("icon.ico"),IMAGE_ICON,0,0,LR_DEFAULTSIZE | LR_LOADFROMFILE);
	wc.lpszClassName = TEXT("DIRECTX");
	wc.lpszMenuName = NULL;
	wc.lpfnWndProc = WNDPROC(WndProc);


	if(!RegisterClassEx(&wc))
	{
		MessageBox(0,TEXT("RegisterClassEx Error!"),0,0);
		return false;
	}

	HWND hwnd = 0;
	hwnd = CreateWindowEx(WS_EX_TOPMOST,TEXT("DIRECTX"),TEXT("DIRECTX"),WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,640,480,NULL,NULL,hInstance,NULL);

	if(!hwnd)
	{
		MessageBox(0,TEXT("CreateWindowEx() Error!"),0,0);
		return false;
	}

	MoveWindow(hwnd, 50,20,1280,720,true);

	ShowWindow(hwnd,SW_SHOW);

	UpdateWindow(hwnd);

	///////////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////
	HRESULT hr;

	IDirect3D9 *d3d9 = 0;
	d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
	
	if (!d3d9)
	{
		MessageBox(0,TEXT("Direct3DCreate9 Error!"),0,0);
		return false;
	}

	///////////////////////////////////////////////////////////////////////////////
	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;

	///////////////////////////////////////////////////////////////////////////////
	D3DPRESENT_PARAMETERS d3dpp;
	d3dpp.BackBufferWidth            = 640;
	d3dpp.BackBufferHeight           = 480;
	d3dpp.BackBufferFormat           = D3DFMT_A8R8G8B8;
	d3dpp.BackBufferCount            = 1;
	d3dpp.MultiSampleType            = D3DMULTISAMPLE_NONE;
	d3dpp.MultiSampleQuality         = 0;
	d3dpp.SwapEffect                 = D3DSWAPEFFECT_DISCARD; 
	d3dpp.hDeviceWindow              = hwnd;
	d3dpp.Windowed                   = TRUE;
	d3dpp.EnableAutoDepthStencil     = true; 
	d3dpp.AutoDepthStencilFormat     = D3DFMT_D24S8;
	d3dpp.Flags                      = 0;
	d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
	d3dpp.PresentationInterval       = D3DPRESENT_INTERVAL_IMMEDIATE;

	hr = d3d9->CreateDevice(
		D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		hwnd,
		vp,
		&d3dpp,
		&Device);

	if( FAILED(hr) )
	{
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

		hr = d3d9->CreateDevice(
			D3DADAPTER_DEFAULT,
			D3DDEVTYPE_HAL,
			hwnd,
			vp,
			&d3dpp,
			&Device);

		if( FAILED(hr) )
		{
			d3d9->Release();
			MessageBox(0, TEXT("CreateDevice() - FAILED"), 0, 0);
			return false;
		}
	}

	SAFE_RELEASE(d3d9);

	///////////////////////////////////////////////////////////////////////////////
	if(!Setup())
	{
		MessageBox(0, TEXT("Setup() - FAILED"), 0, 0);
		return 0;
	}

	EnterMsgLoop( Display );

	Clearup();

	Device->Release();

	return 0;
}


float Get_FPS()
{
	static float fps = 0.0f;
	static int frameCounts = 0;
	static float currentTime = 0.0f;
	static float lastTime = 0.0f;

	frameCounts++;

	currentTime = timeGetTime() * 0.001f;

	if(currentTime - lastTime > 1.0f)
	{
		fps = float(frameCounts) / (currentTime - lastTime);
		lastTime = currentTime;
		frameCounts = 0;
	}

	return fps;
}



阅读更多
个人分类: d3d9
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭