3 Replies - 2822 Views - Last Post: 10 November 2012 - 04:50 PM Rate Topic: -----

#1 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Direct X10 simple window problem at compile time - very frustrating

Posted 06 November 2012 - 03:31 AM

HI all and thanks for reading.
I am currently undertaking DirectX at Uni and was wondering if I could get a heads up as to whats wrong in my code.
Firstly, I must statethat I have tried to build this window from scratch (meaning i didnt use the simple sample provided by Microsoft in the DXD10 SDK sample browser )
Secondly, I am new to this, I have coding experience through two years of general computing covering multiple aspects as part of my degree but this stuff is gnarly!

My Question:
When I compile the window its does indeed compile, but when the code gets to the point where it fills the client back buffer window with a color it then goes on to point to something(at a guess the client back buffer window), it is here that it goes wrong and I just wanna know what I have missed or have incoreectly coded to make this happen >

Code where the problem seems to occur during debug
		// clear the target buffer
		pD3DDevice->ClearRenderTargetView(pRenderTargetView, D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f));

		// Create and Initialize the destination rectangle
		RECT rc; //when the code gets this point here the problems start for me and i cant seem to follow it correctly :(/>
		SetRectEmpty(&rc);



The whole d3d window code

/*
*************************************************************************************************************
*	BUT SOMETHING IS WRONG																				    *
* Gareth`s first  attempt at copying and rehashing the windows setup process to get a window to the screen  *
* Remember peepz ............... FUN + ACTION ...........= FUNCTION................							*
*																											*
* Compiled successfully on 30/09/2012 @ 13:43* (produces blank window prior to insert of direct X)			*
*************************************************************************************************************
*/
//include windows header file, needed for all windows applications it would seem
#include <windows.h>
#include <tchar.h>
#include "resource.h"
#include <d3d10.h>
#include <d3dx10.h>


HINSTANCE hInst; //global handle to instance of application
HWND mainhWnd;  //global var to hold the window handle during program

//define window object height and width
int windowWidth = 640;
int windowHeight = 480;

//Direct 3d globals
/*
*************************************************************************************
* There are 3 pointers created here...												*
* one for device, one for swap chain, one for the render target view				*
*************************************************************************************
*/
ID3D10Device* pD3DDevice = NULL;					//point to d3d device and give it a null value
IDXGISwapChain* pSwapChain = NULL;					//point to dx swapchain and give it a null value
ID3D10RenderTargetView* pRenderTargetView = NULL;	//point to d3d render target view and give it a null value

//font declarations
ID3DX10Font* pFont = NULL;							//font to draw text 
ID3DX10Sprite* pFontSprite = NULL;					//sprite to draw text by batching (spritebatching)
//Font BlendState declarations to hld current blendstate
ID3D10BlendState*		pOriginalBlendState10 = NULL;
ID3D10BlendState*       pFontBlendState10 = NULL;

//forward declarations 
bool InitWindow( HINSTANCE hInstance, int width, int height );
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM );


/************************************************************************************************
*************************************   *****   *****   *****************************************
*************************************   *****   *****   *****************************************
*************************************           *****   *****************************************
*************************************           *****   *****************************************
*************************************   *****   *****   *****************************************
*************************************   *****   *****   *****************************************
*************************************************************************************************
* The function below is basically the setup needed to create a message loop n get d3dx.         *
* It can be seen as the part of the program that recieves messages from the rest of the system  *
* This all allows the program to run in a windows environment- phew its quite a bit really.     *
* NOTEadditional handling scenarios would appear to work best  with PeekMessage(), this         *
* is due to the GetMessage() function waiting to return to the call in opposition               *
* to PeekMessage(), whereby the call is returned immediately.                                   *
* The PeekMessage function can be seen as crucial to game programming with d3dX, because it     *
* can allow the programmer to process additional logic through the loop allowing the program    *
* throughput, with respect to processor intensity, to be updated every loop and thusly increase *
*Performance. Without PeekMessage() everything would slow down once the message que was full of *
*message containers waiting to be fired back only when they are message ready-                  *
*(have something in it)                                                                         *
*************************************************************************************************/
//D3D functions 
//(must be prototyped as compiler would not see them before they are called and throw "identifier not found" error)

bool InitDirect3D(HWND, int width, int height);
void ShutdownDirect3D();
void Render();

//Font functions
bool InitFont();
void GetFontRectangle(LPCWSTR text, RECT *rect);


//This is winmain , the main entry point for the windows program
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
	// save off the instance handle
	hInst = hInstance; 

	//initialize program window
	if (!InitWindow(hInstance, windowWidth, windowHeight))
	{
		return false;
	}
	// Initialize Direct3D
	if (!InitDirect3D(mainhWnd, windowWidth, windowHeight))
	{
		return 0;
	}

	// initialize fonts
	if (!InitFont())
	{
		return 0;
	}

	//main messgae loop
	MSG msg = {0};
	while (WM_QUIT != msg.message)
	{
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) == TRUE)
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		//other game logic goes below here
		Render();
	}

	//clean up resources allocated
	ShutdownDirect3D();

	return (int) msg.wParam;



}

/****************************************************************
* Init window													*
* initializes and creates main application window				*
* Inputs- application instance  - HINSTANCE						*
*		Window width - int										*
*		Window height - int										*
*		Outputs - true if successful, flase if failed - bool	*
*****************************************************************/
bool InitWindow(HINSTANCE hInstance, int width, int height)
{
	WNDCLASSEX wcex;

	//fill in the WNDCLASSEX structure that describes how the window will look to the system.
	wcex.cbSize = sizeof(WNDCLASSEX);				//size of structure
	wcex.style = CS_HREDRAW | CS_VREDRAW;			//class style
	wcex.lpfnWndProc = (WNDPROC)WndProc;			//callback for window procedure
	wcex.cbClsExtra = 0;							//extra bytes to allocate to this class
	wcex.cbWndExtra = 0;							//extra bytes to allocate for this instance
	wcex.hInstance = hInstance;						//handle to the program instance
	wcex.hIcon = 0;									//associate icon to the program but why ?
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);		//default cursor (normal windows mouse pointer"IDC_ARROW")
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);	//background colour
	wcex.lpszMenuName = NULL;						//menu resource name
	wcex.lpszClassName = TEXT("GruffyTemplate");	//class name to create
	wcex.hIconSm = 0;								//handle to the small program icon
	RegisterClassEx(&wcex);							//register class with reference to its parameters

	//create  window
	RECT rect = {0, 0, width, height};
	AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, false);

	//create the window from the class above
	mainhWnd = CreateWindow(TEXT("GruffyTemplate"),
		TEXT("GruffyTemplate"),
		WS_OVERLAPPEDWINDOW, 
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		rect.right - rect.left,
		rect.bottom - rect.top,
		NULL,
		NULL,
		hInstance,
		NULL);

	if (!mainhWnd)
	{
		return false;
	}

	/*window view entry point*/
	//Display window on screen

	ShowWindow (mainhWnd, SW_SHOW);
	UpdateWindow(mainhWnd);

	return true;

} 

/*
*********************************************************************************************
* wndProc																					*
* The main window procedure for the progam													*
* Inputs-	application handle for wind - HWND												*
*				message sent to window as- UINT (unsigned integer, must be positive)	    *
*				w(word)Param of message beign sent (16bit) - WPARAM							*
*				l(long)Param of message being sent (32 bit) - LPARAM						*
*																							*
* Output is in - LRESULT																	*
*********************************************************************************************
*/
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	//check available messages form the queue
	switch(message)
	{
		//allow the user to press escape to end program
	case WM_KEYDOWN:
		switch(wParam)
		{
			//check if the user hit escape
		case VK_ESCAPE:
			PostQuitMessage(0);
			break;
		}
		//I CAN ADD D3D KEYBOARD INPUT INTO HERE
				break;

				//check if user hit close  button on window, if so quit program
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}
	//always return a message to the default window proc for further processing - if its needed
	return DefWindowProc(hWnd, message, wParam, lParam );
}

/*
*****************************************************
* InitDirect3D										*
* Initializes direct3D								*
* Inputs- Parent window handle - HWND				*
*			Window width - int						*
*			Window height - int						*
*													*
*  Outputs success = true, failure = false - bool	*
*****************************************************
*/

bool InitDirect3D(HWND hWnd, int width, int height)
{
	//create and clear DXGI_SWAP_CHAIN_DESC structure
	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	//fill in needed values to instantiate swapchain object
	swapChainDesc.BufferCount = 1;
	swapChainDesc.BufferDesc.Width = width;
	swapChainDesc.BufferDesc.Height = height;
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
	swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	swapChainDesc.OutputWindow = hWnd;
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;
	swapChainDesc.Windowed = TRUE;

/*
*************************************************************
* Attempt to create a hardware device followed by reference *
* device if hardware device fails							*
*************************************************************
*/
	//declare and initialize driver type with null
	D3D10_DRIVER_TYPE driverType = D3D10_DRIVER_TYPE_NULL;
	//define array with types of driver services ( 1 for onboard REFERENCE, 1 for GC HARDWARE )
	D3D10_DRIVER_TYPE driverTypes[] = { D3D10_DRIVER_TYPE_HARDWARE, D3D10_DRIVER_TYPE_REFERENCE };

	UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]);

	//loop through available driver types and attempt to create the hardware device 1st (graphic card 1st)
	for(UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
	{
		driverType = driverTypes[driverTypeIndex];

	//create the 3d device and swap chain
		HRESULT hr = D3D10CreateDeviceAndSwapChain(NULL,
												D3D10_DRIVER_TYPE_HARDWARE,
												NULL,
												0,
												D3D10_SDK_VERSION,
												&swapChainDesc,
												&pSwapChain,
												&pD3DDevice);

		////start if all is good
		if (SUCCEEDED(hr))
			break;
				
		// Error checking. Make sure the device was created, if failed send error message to screen
		if (FAILED(hr))
		{
			MessageBox(hWnd, TEXT("A DX10 Compliant VC needed to play this "), TEXT("ERROR"), MB_OK);
			//ensure device is definitely released
			//HI NIGEL, IS THE BELOW RELEASE METHOD EVEN WORTH DOING, my reasoning is to ensure nothing is left in memory that might have sneakily got stored during the device creation process prior to the fail point.
			//I dont know if this is something or nothing, just wondered if you knew whether im barking mad even bothering or might have a point.
			pD3DDevice->Release();
			return false;
		}


		//get the back buffer from the swapchain
		ID3D10Texture2D *pBackBuffer;
		hr = pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer);
		//otherwise if device not created  terminate compilation/ program execution, shutdown program z zt ztz  zztzzztt bang poooooohfff
		if (FAILED(hr))
		{
			return false;
		}

		//create the render target view
		hr = pD3DDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRenderTargetView);

		//release the back buffer
		pBackBuffer->Release();

		//make sure render target view was successful
		if (FAILED(hr))
		{
			return false;
		}

		//set the render target
		pD3DDevice->OMSetRenderTargets(1, &pRenderTargetView, NULL);

		//create and set d3d viewport
		D3D10_VIEWPORT viewPort;
		viewPort.Width = width;
		viewPort.Height = height;
		viewPort.MinDepth = 0.0f;
		viewPort.MaxDepth = 1.0f;
		viewPort.TopLeftX = 0;
		viewPort.TopLeftY = 0;
		pD3DDevice->RSSetViewports( 1, &viewPort );


	}
			//confirm is built ..
		return true;

}

	/*
	*********************************************
	* void ShutdownDirect3d						*
	* closes down and releases d3d				*
	* resources/objects							*
	* Inputs - void								*
	* Outputs - void							*
	*********************************************
	*/
	void ShutdownDirect3D()
	{
		// Release the original blend state object
		if (pOriginalBlendState10 != NULL)
		{
			pOriginalBlendState10->Release();
			pOriginalBlendState10 = NULL;
		}

		// Release the font blend state object
		if (pFontBlendState10 != NULL)
		{
			pFontBlendState10->Release();
			pFontBlendState10 = NULL;
		}
		
	//release font
		if(pFont != NULL)
		{
			pFont->Release();
			pFont = NULL;
		}
	//release fontsprite
		if(pFontSprite != NULL)
		{
			pFontSprite->Release();
			pFontSprite = NULL;
		}
		//RELEASE RENDERtARGET
		if(pRenderTargetView)
		{
			pRenderTargetView->Release();
		}

		//release swapchain
		if(pSwapChain)
		{
			pSwapChain->Release();
		}

		//release D3D device
		if (pD3DDevice)
		{
			pD3DDevice->Release();
		}
	}

	/*
	*********************************************
	* Render									*
	* All drawing is done in render function	*
	* Inputs - void								*
	* Outputs - Void too						*
	*********************************************
	*/
void Render()
{
	FLOAT OriginalBlendFactor[4];
    UINT  OriginalSampleMask = 0;

	if (pD3DDevice != NULL)
	{
		// clear the target buffer
		pD3DDevice->ClearRenderTargetView(pRenderTargetView, D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f));

		// Create and Initialize the destination rectangle
		RECT rc;
		SetRectEmpty(&rc);

		// Use the GetFontRectangle helper function to get the proper size of the rectangle.
		GetFontRectangle(TEXT("This is a test string"), &rc);

		// Start font drawing
		pFontSprite->Begin(D3DX10_SPRITE_SORT_TEXTURE);

		// Draw the text to the screen
		HRESULT hr = pFont->DrawText( pFontSprite, TEXT("This is a test string"), -1, &rc, DT_LEFT, D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) );
	
		// Save the current blend state
		pD3DDevice->OMGetBlendState(&pOriginalBlendState10, OriginalBlendFactor, &OriginalSampleMask);

		// Set the blend state for font drawing
		if(pFontBlendState10)
        {
            FLOAT NewBlendFactor[4] = {0,0,0,0};
			pD3DDevice->OMSetBlendState(pFontBlendState10, NewBlendFactor, 0xffffffff);
		}

		pFontSprite->End();

		// Restore the previous blend state
		pD3DDevice->OMSetBlendState(pOriginalBlendState10, OriginalBlendFactor, OriginalSampleMask);

		// display the next item in the swap chain
		pSwapChain->Present(0, 0);
	}

}

/*
*************************************************************************************************************
************************************ADDITIONAL*NOTE* FOR* PEOPLE* LIKE* ME******************************************************
*One of the most important aspects of getting this to work was found in the liking of the directX			*
* libraries and headers.																					*
* This is a difficult to find easily 3 step process to complete manually which ensures directX is setup		*
* and might be a good practice to check over for any directX builds....										*
* Step 1:																									*
*	Configuration Properties->C/C++->General and set the full path for the *header* (*.h) files in			*
*	"Additional Include Directories".																		*
* Step 2:																									*
*	Configuration Properties->Linker->General and set the full path for the .lib files in					*
*	"Additional Library Directories"																		*
* Step 3:																									*
*	Configuration Properties->Linker->Input and set the .lib file name (d3d10.lib) in						*
*	"Additional Dependencies"																				*
*																											*
* This will ensure you are accurately linked to the correct DirectX SDK 2010 folders.						*
*																											*
*Just in case you didnt know, when setting the paths use the User interface, click it, then click "Edit" and			*
* navigate to the folder....mine was "C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include" &	*
* "C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib" this should the same or similar			*
*************************************************************************************************************
*/
/*
*********************************************
*GetFontRectangle							*
* Resizes font dest rectangle				*
* Input- LPCWSTR - text to be drawn			*
*		 RECT - pointer to rect to return	*
*********************************************
*/
	void GetFontRectangle(LPCWSTR text, RECT *rect)
	{
		//use DT_CALCRECT to determine rect but not draw it
		pFont->DrawText(NULL, 
							text,
							-1,
							rect,
							DT_CALCRECT | DT_LEFT,
							D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f));
	}
/*
*****************************************************
* InitFont											*
* Initialize the font object						*
* Inputs - void										*
* Outputs - bool - true/ success, false/ failure		*
*****************************************************
*/
bool InitFont()
{
	HRESULT hr = D3DX10CreateFont(pD3DDevice,
		35,											// font height
		0,											// font width
		FW_BOLD,									// font weight
		1,											// mip levels
		FALSE,										// not italic
		DEFAULT_CHARSET,							// default character set
		OUT_DEFAULT_PRECIS,							// size mapping = default
		DEFAULT_QUALITY,							// qualilty mapping = default
		DEFAULT_PITCH | FF_DONTCARE,				// pitch = default or does not matter
		L"Helvetica",							// Use Helvetica
		&pFont);									// Output

	//make sure font wwas created 
	if(FAILED(hr))
	{
		return false;
	}
	//Create sprite that fontd will use to draw with
	D3DX10CreateSprite(pD3DDevice, 512, &pFontSprite);

	// Initialize the blend state for font drawing
	D3D10_BLEND_DESC StateDesc;
    ZeroMemory(&StateDesc, sizeof(D3D10_BLEND_DESC));
    StateDesc.AlphaToCoverageEnable = FALSE;
    StateDesc.BlendEnable[0] = TRUE;
    StateDesc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
    StateDesc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
    StateDesc.BlendOp = D3D10_BLEND_OP_ADD;
    StateDesc.SrcBlendAlpha = D3D10_BLEND_ZERO;
    StateDesc.DestBlendAlpha = D3D10_BLEND_ZERO;
    StateDesc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
    StateDesc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
    pD3DDevice->CreateBlendState(&StateDesc, &pFontBlendState10);

	return true;

}








Thanks in advance for any help that anyone can give.
A very confused/frustrated/ but still happy Gruffy
PS I have included zip file of project but not sure if correctly zipped, the size seems to be fairly large if i included the ipch files and sql stuff, so i have not included them, if this is needed, then just let me know and i will upload to dropbox or somehting and link to it from here. But what i have provided shoud be enough to build the project anyway i think.
Thanks and thanks again ! :):):)

Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: Direct X10 simple window problem at compile time - very frustrating

#2 anonymous26  Icon User is offline

  • D.I.C Lover

Reputation: 0
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: Direct X10 simple window problem at compile time - very frustrating

Posted 10 November 2012 - 07:26 AM

What happens if you build from the sample?
Was This Post Helpful? 1
  • +
  • -

#3 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Re: Direct X10 simple window problem at compile time - very frustrating

Posted 10 November 2012 - 10:12 AM

Hey ButchDean,
Its all good if i use the Microsoft sample. VS2010 coompiles and runs fine
My main frustration is that i am lost in the debugger when it tries to reference "(&ptd)", it loses me as to why it bums out/ throws the runtime exception, it must be the way i have placed some code but im stumped.
I guess i have to move on as time is a factor really, i supposed to have a set of wings attached to a sample mesh that flap according to the mesh (parented to it etc.


Direct X10 seems like it might have regressed since its direct x 9 fixed functions abandonment and I believe there are more supporters for version 11 as it has returned somehwat to a friendlier implementation, but 10 is what i have to learn :( oh well understanding a commonly agreed upon worse api should give an insight when looking at improved implementations i guess.
dunno , hope so cos its a pain in bum

thanks for reply ButchDean
gruffy
Was This Post Helpful? 0
  • +
  • -

#4 anonymous26  Icon User is offline

  • D.I.C Lover

Reputation: 0
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: Direct X10 simple window problem at compile time - very frustrating

Posted 10 November 2012 - 04:50 PM

No problem, gruffy. What is the exception thrown, btw? That will give a lot of clues.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1