Skip to main content
GameDev.net gamedev.net
🔒 Locked

Runtime problem with CreateWindow() with code from Frank Luna's book

Started by blart Dec 8, 2007 at 4:22 PM 5 replies 2.7k views
Original Post
blart
blart
well i'm new to directx! so i got a book ("introduction to 3D game programming with directx9" by Frank D. Luna) and i started doing some examples in code so i could see theory in action... well my compiler (visual studio 2005 pro) seems to having problem with the createwindow() method!!!! here's my code(some things borrowed by the author):
#include "d3dUtility.h"


IDirect3DDevice9* Device = 0;
IDirect3DVertexBuffer9* VB = 0;
IDirect3DIndexBuffer9* IB = 0;

const int width=800;
const int height=600;

struct Vertex
{
	Vertex(){}
	Vertex(float x, float y, float z)
	{
		x=x; y=y; z=z;
	}
	float x,y,z;
	static const DWORD FVF;
};
const DWORD Vertex::FVF = D3DFVF_XYZ;


bool Setup()
{
	Device->CreateVertexBuffer(3*sizeof(Vertex), D3DUSAGE_WRITEONLY, Vertex::FVF, D3DPOOL_MANAGED, &VB, 0);
	Device->CreateIndexBuffer(3*sizeof(WORD), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &IB, 0);

	Vertex* vcs;
	VB->Lock(0, 0, (void**)&vcs, 0);
	vcs[0] = Vertex(-2.0f, -1.0f, 0.0f);
	vcs[1] = Vertex(1.0f, 2.0f, 0.0f);
	vcs[2] = Vertex(2.0f, -2.0f, 0.0f);
	VB->Unlock();

	WORD* inds;
	IB->Lock(0, 0, (void**)&inds, 0);
	inds[0]=0; inds[1]=1; inds[2]=2;
	IB->Unlock();

	D3DXVECTOR3 position(0.0f, 0.0f, -5.0f);
	D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
	D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
	D3DXMATRIX V;
	D3DXMatrixLookAtLH(&V, &position, ⌖, &up);

	Device->SetTransform(D3DTS_VIEW, &V);

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

	Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);

	return true;
}

void Cleanup()
{
	d3d::Release<IDirect3DVertexBuffer9*>(VB);
	d3d::Release<IDirect3DIndexBuffer9*>(IB);
}

bool Display(float timeDelta)
{
	if( Device ) // Only use Device methods if we have a valid device.
	{
		Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0);

		Device->BeginScene();
		Device->SetStreamSource(0, VB, 0, sizeof(Vertex));
		Device->SetIndices(IB);
		Device->SetFVF(Vertex::FVF);
		Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 3, 0, 1);
		Device->EndScene();

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

#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__


#include "d3dUtility.h"
#include <windows.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 = "D3D";

	if( !RegisterClass(&wc) ) 
	{
		::MessageBox(0, "RegisterClass() - FAILED", 0, 0);
		return false;
	}
		
	HWND hwnd=0;
	hwnd = ::CreateWindowEx(WS_EX_APPWINDOW, "Direct3D9App", "Direct3D9App", 
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT, width, height,
		NULL, NULL, hInstance, NULL); 

	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, ∩︀);

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

well there's no compiling errors or warnings, but every time i run the program, i get a message box telling me: "CreateWindow() - FAILED"!!! what is the problem?? i searched everywhere... any help appreciated!! [Edited by - jollyjeffers on December 8, 2007 6:42:52 PM]
Costas
Namethatnobodyelsetook
Namethatnobodyelsetook
You are registering a class called "D3D", and then asking to make a window of class "Direct3D9App". Since no such class exists, create window fails.
MJP
MJP
You're registering your window class with one name ("D3D"), and then specifying another when you call CreateWindow ("Direct3D9App"). Check the documentation for RegisterClass() and CreateWindow() for more info.

Also, in the future please use the "source" tags when posting long bits of code. :D
blart
blart
thnx guys!! it works now!! (not a genius in windows prog :P)
Costas
Nuno1
Nuno1
You better start using GetLastError. those kind of errors can be solves easyly by this function.

GetLastError will provide you with an error code which you can resolve after a WinAPI function fails.

just my 2 cents.
Nuno1
jollyjeffers
jollyjeffers
For reference please consider 3 things:

  1. "why isn't it working???" is not a suitable subject line. In future please pick a more descriptive subject line - it helps the many helpful forum regulars to pick threads they might be able to help with. Lots of people will ignore badly named threads.

  2. Please use [source]...[/source] tags around your code. Dumping 100's of lines of text into your post is not readable at best, especially given web rendering doesn't tend to preserve whitespace [wink]

  3. Consider your audience. You quite correctly identified this as a runtime and non compile-time error, so quite how do you expect us to use static code analysis to determine the cause of the error? In this instance it was possible, but for future reference you might want to consider what information it is best to present alongside your question. What might we find useful in order to help you? Note that very very few people will trust arbitrary code posted in a forum and expecting people to try and execute and debug your code for you is wishful thinking.


Happy coding [smile]

Jack
<hr align="left" width="25%" />
Jack Hoxley <small>[</small><small> Forum FAQ | Revised FAQ |
blart
blart
Quote:
Original post by jollyjeffers
For reference please consider 3 things:

  1. "why isn't it working???" is not a suitable subject line. In future please pick a more descriptive subject line - it helps the many helpful forum regulars to pick threads they might be able to help with. Lots of people will ignore badly named threads.

  2. Please use [source]...[/source] tags around your code. Dumping 100's of lines of text into your post is not readable at best, especially given web rendering doesn't tend to preserve whitespace [wink]

  3. Consider your audience. You quite correctly identified this as a runtime and non compile-time error, so quite how do you expect us to use static code analysis to determine the cause of the error? In this instance it was possible, but for future reference you might want to consider what information it is best to present alongside your question. What might we find useful in order to help you? Note that very very few people will trust arbitrary code posted in a forum and expecting people to try and execute and debug your code for you is wishful thinking.


Happy coding [smile]

Jack


ok, thanks for the tips!!
Costas

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.