game.cpp

来自「对游戏编程感兴趣的 朋友可以 下载下来看看 对DX讲解的很很详细」· C++ 代码 · 共 949 行 · 第 1/2 页

CPP
949
字号
// Game.cpp: implementation of the CGame class.
//
//////////////////////////////////////////////////////////////////////

#include "Game.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CGame::CGame()
{
	m_pD3D = NULL;
	m_pD3DDevice = NULL;
	m_pDirectInput = NULL;
	m_pKeyboard = NULL;
	m_pMouse = NULL;
	m_pDirectAudioPerformance = NULL;
	m_pDirectAudioLoader = NULL;

	m_dwFrames = 0;
	m_dwStartTime = 0;
	m_dwEndTime = 0;
	m_dwTotalPolygons = 0;
	m_fQuit = false;

	//Initialise COM
	CoInitialize(NULL);

	m_nMouseLeft = 0;
	m_nMouseRight = 0;
	m_nMouseX = 0;
	m_nMouseY = 0;
	m_pFont = NULL;
	
	m_pSound1 = NULL;
	m_pSound2 = NULL;
	m_pSound3 = NULL;
	m_pSound4 = NULL;
	m_pSoundFailed = NULL;
	m_pSoundBG = NULL;

	m_pPanelMouse = NULL;
	m_pPanel1 = NULL;
	m_pPanel2 = NULL;
	m_pPanel3 = NULL;
	m_pPanel4 = NULL;
}

CGame::~CGame()
{
	//Game finished, so destroy game objects
	LogInfo("<br>Finish Game:");

	//Clean up our objects and interfaces
	CleanUpGame();
	CleanUpDirectAudio();
	CleanUpDirectInput();
	CleanUpDirect3D();

	CoUninitialize();

	//Game finished, so save statistics to log
	DWORD dwDuration = (m_dwEndTime - m_dwStartTime) / 1000;
	
	if((dwDuration != 0)&&(m_dwFrames != 0))
	{
		//Log stats
		LogInfo("<br>Statistics:");
		LogInfo("<li>Start Time (ms): %d", m_dwStartTime);
		LogInfo("<li>End Time (ms): %d", m_dwEndTime);
		LogInfo("<li>Duration (s): %d", dwDuration);
		LogInfo("<li>Total Frame Count: %d", m_dwFrames);
		LogInfo("<li>Average FPS: %d", (m_dwFrames / dwDuration));
		LogInfo("<li>Total Polygons: %d", m_dwTotalPolygons);
		LogInfo("<li>Average Polygons per Frame: %d", (m_dwTotalPolygons / m_dwFrames));
	}
	else
	{
		LogInfo("<br>No statistics to report");
	}

	StopLogging();
}

void CGame::CleanUpGame()
{
	SafeDelete(m_pFont);
	SafeDelete(m_pSound1);
	SafeDelete(m_pSound2);
	SafeDelete(m_pSound3);
	SafeDelete(m_pSound4);
	SafeDelete(m_pSoundFailed);
	SafeDelete(m_pSoundBG);

	SafeDelete(m_pPanelMouse);
	SafeDelete(m_pPanel1);
	SafeDelete(m_pPanel2);
	SafeDelete(m_pPanel3);
	SafeDelete(m_pPanel4);
}

void CGame::CleanUpDirectAudio()
{
	//Stop all sounds.
	m_pDirectAudioPerformance->Stop(NULL, NULL, 0, 0);
 
	//CleanUp
    m_pDirectAudioPerformance->CloseDown();
 
    SafeRelease(m_pDirectAudioLoader);
    SafeRelease(m_pDirectAudioPerformance);

	LogInfo("<li>CleanUpDirectAudio finished.");
}

void CGame::CleanUpDirectInput()
{
	if(m_pKeyboard)
	{
		m_pKeyboard->Unacquire(); 
	}

	if(m_pMouse)
	{
		m_pMouse->Unacquire();
	}

	SafeRelease(m_pMouse);
	SafeRelease(m_pKeyboard);
	SafeRelease(m_pDirectInput);

	LogInfo("<li>CleanUpDirectInput finished.");
}

void CGame::CleanUpDirect3D()
{
	SafeRelease(m_pD3DDevice);
	SafeRelease(m_pD3D);

	LogInfo("<li>CleanUpDirect3D finished.");
}

bool CGame::Initialise(HWND hWnd, HINSTANCE hInst, UINT nWidth, UINT nHeight)
{
	//Initialise Direct3D
	if(!InitialiseDirect3D(hWnd, nWidth, nHeight))
	{
		return false;
	}
	
	//Initialise DirectInput
	if(!InitialiseDirectInput(hWnd, hInst))
	{
		return false;
	}
	
	if(!InitialiseDirectAudio(hWnd))
	{
		return false;
	}

	//Initialise Lighting
	if(!InitialiseLights()) 
	{
		return false;
	}

	//Initialise Game Objects
	if(!InitialiseGame())
	{
		return false;
	}

	return true;
}

bool CGame::InitialiseGame()
{
	LogInfo("<br>Initialise Game:");

	//Setup games objects here
	

	//Setup fonts here
	m_pFont = new CFont(m_pD3DDevice, "Verdana", 12, false, false, false);

	//Setup panels for 2D
	m_pPanelMouse = new CPanel(m_pD3DDevice, 32, 32, m_nScreenWidth, m_nScreenHeight);
	m_pPanelMouse->SetTexture("Textures\\Mouse.bmp", D3DCOLOR_XRGB(0, 0, 0));

	m_pPanel1 = new CPanel(m_pD3DDevice, 128, 128, m_nScreenWidth, m_nScreenHeight);
	m_pPanel1->SetTexture("Textures\\1.bmp");

	m_pPanel2 = new CPanel(m_pD3DDevice, 128, 128, m_nScreenWidth, m_nScreenHeight);
	m_pPanel2->SetTexture("Textures\\2.bmp");

	m_pPanel3 = new CPanel(m_pD3DDevice, 128, 128, m_nScreenWidth, m_nScreenHeight);
	m_pPanel3->SetTexture("Textures\\3.bmp");

	m_pPanel4 = new CPanel(m_pD3DDevice, 128, 128, m_nScreenWidth, m_nScreenHeight);
	m_pPanel4->SetTexture("Textures\\4.bmp");

	//Setup sounds
	m_pSound1 = new CSound();
	m_pSound1->InitialiseForWavMidi(m_pDirectAudioPerformance, m_pDirectAudioLoader);
	m_pSound1->LoadSound("notify.wav");

	m_pSound2 = new CSound();
	m_pSound2->InitialiseForWavMidi(m_pDirectAudioPerformance, m_pDirectAudioLoader);
	m_pSound2->LoadSound("chimes.wav");

	m_pSound3 = new CSound();
	m_pSound3->InitialiseForWavMidi(m_pDirectAudioPerformance, m_pDirectAudioLoader);
	m_pSound3->LoadSound("chord.wav");

	m_pSound4 = new CSound();
	m_pSound4->InitialiseForWavMidi(m_pDirectAudioPerformance, m_pDirectAudioLoader);
	m_pSound4->LoadSound("ding.wav");

	m_pSoundFailed = new CSound();
	m_pSoundFailed->InitialiseForWavMidi(m_pDirectAudioPerformance, m_pDirectAudioLoader);
	m_pSoundFailed->LoadSound("Fail.wav");

	m_pSoundBG = new CSound();
	m_pSoundBG->InitialiseForMP3();
	m_pSoundBG->LoadSound("Aai_Took-Needthew-3776_hifi.mp3");

	return true;
}

D3DFORMAT CGame::CheckDisplayMode(UINT nWidth, UINT nHeight, UINT nDepth)
{
	UINT x;
	D3DDISPLAYMODE d3ddm;

	for(x = 0; x < m_pD3D->GetAdapterModeCount(0); x++)
	{
		m_pD3D->EnumAdapterModes(0, x, &d3ddm);
		if(d3ddm.Width == nWidth)
		{
			if(d3ddm.Height == nHeight)
			{
				if((d3ddm.Format == D3DFMT_R5G6B5) || (d3ddm.Format == D3DFMT_X1R5G5B5) || (d3ddm.Format == D3DFMT_X4R4G4B4))
				{
					if(nDepth == 16)
					{
						return d3ddm.Format;
					}
				}
				else if((d3ddm.Format == D3DFMT_R8G8B8) || (d3ddm.Format == D3DFMT_X8R8G8B8))
				{
					if(nDepth == 32)
					{
						return d3ddm.Format;
					}
				}
			}
		}
	}

	return D3DFMT_UNKNOWN;
}

bool CGame::InitialiseDirectAudio(HWND hWnd)
{
	LogInfo("<br>Initialise DirectAudio:");


	//Create the DirectAudio performance object
	if(CoCreateInstance(CLSID_DirectMusicPerformance, NULL, CLSCTX_INPROC, 
						IID_IDirectMusicPerformance8, (void**) &m_pDirectAudioPerformance) != S_OK)
	{
		LogError("<li>Failed to create the DirectAudio perfomance object.");
		return false;
	}
	else
	{
		LogInfo("<li>DirectAudio perfomance object created OK.");
	}

	//Create the DirectAudio loader object
	if(CoCreateInstance(CLSID_DirectMusicLoader, NULL, CLSCTX_INPROC, 
						IID_IDirectMusicLoader8, (void**) &m_pDirectAudioLoader) != S_OK)
	{
		LogError("<li>Failed to create the DirectAudio loader object.");
		return false;
	}
	else
	{
		LogInfo("<li>DirectAudio loader object created OK.");
	}

	//Initialise the performance object
	if(FAILED(m_pDirectAudioPerformance->InitAudio(NULL, NULL, hWnd, DMUS_APATH_SHARED_STEREOPLUSREVERB,
										 64, DMUS_AUDIOF_ALL, NULL)))
	{
		LogError("<li>Failed to initialise the DirectAudio perfomance object.");
		return false;
	}
	else
	{
		LogInfo("<li>Initialised the DirectAudio perfomance object OK.");
	}



	//Get the our applications "sounds" directory.
    CHAR strSoundPath[MAX_PATH];
    GetCurrentDirectory(MAX_PATH, strSoundPath);
    strcat(strSoundPath, "\\Sounds");
 
	//Convert the path to unicode.
    WCHAR wstrSoundPath[MAX_PATH];
    MultiByteToWideChar(CP_ACP, 0, strSoundPath, -1, wstrSoundPath, MAX_PATH);
 
    //Set the search directory.
    if(FAILED(m_pDirectAudioLoader->SetSearchDirectory(GUID_DirectMusicAllTypes, wstrSoundPath, FALSE)))
	{
		LogError("<li>Failed to set the search directory '%s'.", strSoundPath);
		return false;
	}
	else
	{
		LogInfo("<li>Search directory '%s' set OK.", strSoundPath);
	}


	return true;
}

bool CGame::InitialiseDirectInput(HWND hWnd, HINSTANCE hInst)
{
	LogInfo("<br>Initialise DirectInput:");

	//Create the DirectInput object
	if(FAILED(DirectInput8Create(hInst, DIRECTINPUT_VERSION, 
			  IID_IDirectInput8, (void**)&m_pDirectInput, NULL))) 
	{ 
		LogError("<li>Unable to create DirectInput interface.");
		return false;
	}
	else
	{
		LogInfo("<li>DirectInput interface created OK");
	}
	
	//KEYBOARD =======================================================================
	//Create the keyboard device object
	if(FAILED(m_pDirectInput->CreateDevice(GUID_SysKeyboard, &m_pKeyboard, NULL))) 
	{ 
		CleanUpDirectInput();
		LogError("<li>Unable to create DirectInput keyboard device interface.");
		return false; 
	}
	else
	{
		LogInfo("<li>DirectInput keyboard device interface created OK.");
	}

	//Set the data format for the keyboard
	if(FAILED(m_pKeyboard->SetDataFormat(&c_dfDIKeyboard)))
	{ 
		CleanUpDirectInput();
		LogError("<li>Unable to set the keyboard data format.");
		return false; 
	}
	else
	{
		LogInfo("<li>Set the keyboard data format OK.");
	}

	//Set the cooperative level for the keyboard
	if(FAILED(m_pKeyboard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
	{ 
		CleanUpDirectInput();
		LogError("<li>Unable to set the keyboard cooperative level.");
		return false;
	}
	else
	{
		LogInfo("<li>Set the keyboard cooperative level OK.");
	}

	//Acquire the keyboard
	if(m_pKeyboard)
	{
		m_pKeyboard->Acquire(); 
	}


	//MOUSE =======================================================================
	//Create the mouse device object
	if(FAILED(m_pDirectInput->CreateDevice(GUID_SysMouse, &m_pMouse, NULL)))
	{ 
		CleanUpDirectInput();
		LogError("<li>Unable to create DirectInput mouse device interface.");
		return false; 
	}
	else
	{
		LogInfo("<li>DirectInput mouse device interface created OK.");
	}

	//Set the data format for the mouse
	if(FAILED(m_pMouse->SetDataFormat(&c_dfDIMouse)))
	{ 
		CleanUpDirectInput();
		LogError("<li>Unable to set the mouse data format.");
		return false; 
	}
	else
	{
		LogInfo("<li>Set the mouse data format OK.");
	}

	//Set the cooperative level for the mouse
	if(FAILED(m_pMouse->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
	{ 
		CleanUpDirectInput();
		LogError("<li>Unable to set the mouse cooperative level.");
		return false;
	}
	else
	{
		LogInfo("<li>Set the mouse cooperative level OK.");
	}

	//Acquire the mouse
	if(m_pMouse)
	{
		m_pMouse->Acquire(); 
	}



	return true;
}

bool CGame::InitialiseDirect3D(HWND hWnd, UINT nWidth, UINT nHeight)
{
	LogInfo("<br>Initialise Direct3D:");

    //First of all, create the main D3D object. If it is created successfully we 
    //should get a pointer to an IDirect3D8 interface.
    m_pD3D = Direct3DCreate8(D3D_SDK_VERSION);
    if(m_pD3D == NULL)
    {
		LogError("<li>Unable to create DirectX8 interface.");
        return false;
    }

    //Get the current display mode
    D3DDISPLAYMODE d3ddm;

	d3ddm.Format = CheckDisplayMode(nWidth, nHeight, 32);
	if(d3ddm.Format != D3DFMT_UNKNOWN)
	{
		//Width x Height x 32bit has been selected
		d3ddm.Width = nWidth;
		d3ddm.Height = nHeight;

		LogInfo("<li>%d x %d x 32bit back buffer format selected. Format = %d.", nWidth, nHeight, d3ddm.Format);
	}
	else
	{
		d3ddm.Format = CheckDisplayMode(nWidth, nHeight, 16);
		if(d3ddm.Format != D3DFMT_UNKNOWN)
		{
            //Width x Height x 16bit has been selected
			d3ddm.Width = nWidth;
			d3ddm.Height = nHeight;

			LogInfo("<li>%d x %d x 16bit back buffer format selected. Format = %d.", nWidth, nHeight, d3ddm.Format);
		}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?