Sign in to follow this  

(It was me Need my * kicked)Debugger Cause's First-chance exception at 0x007363bf

This topic is 3574 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, This is the first time Im using the debugger the app runs ok when not in debug mode but when I set it to debug the app drops out and give me this message. First-chance exception at 0x007363bf in WorldBuilder.exe: 0xC0000005: Access violation reading location 0xfdfdfe1d. Unhandled exception at 0x007363bf in WorldBuilder.exe: 0xC0000005: Access violation reading location 0xfdfdfe1d. the code that the debugger say is broken is this lot here

getViewMatrix(D3DXMATRIX* V)
{
	D3DXMatrixIdentity(V);
	// Keep camera's axes orthogonal to eachother
	D3DXVec3Normalize(&_look, &_look);

Points here 
	    D3DXVec3Cross(&_up, &_look, &_right);
	    D3DXVec3Normalize(&_up, &_up);

	    D3DXVec3Cross(&_right, &_up, &_look);
	    D3DXVec3Normalize(&_right, &_right);
}


the _up and _look and _right are defined in the class like this
class camera
{
public:
D3DXVECTOR3 _right;
	
D3DXVECTOR3 _up;
	
D3DXVECTOR3 _look;
	
D3DXVECTOR3 _pos;
};




this camera class is allocated in the init function at start up like this Camera = new cCamera no errors all ok Using Using Microsoft Visual Studio 2005 Version 8.0.50727.762 (SP.050727-7600) Microsoft .NET Framework Version 2.0.50727 Installed Edition: VC Express XP pro I noted that in the call stack it does not list the init function but the code must be getting processed or it should crash else where here is the call stack
 	d3dx9d_33.dll!007363bf() 	
 	[Frames below may be incorrect and/or missing, no symbols loaded for d3dx9d_33.dll]	
>	WorldBuilder.exe!Camera2::getViewMatrix(D3DXMATRIX * V=0x00483970)  Line 441	C++
 	WorldBuilder.exe!MyAppWin::SetupMatrices()  Line 1589	C++
 	WorldBuilder.exe!MyAppWin::Render()  Line 1414	C++
 	WorldBuilder.exe!WinMain(HINSTANCE__ * hInstance=0x00400000, HINSTANCE__ * hPrevInstance=0x00000000, char * szCmdLine=0x00151f13, int iCmdShow=1)  Line 500	C++
 	WorldBuilder.exe!__tmainCRTStartup()  Line 589 + 0x35 bytes	C
 	WorldBuilder.exe!WinMainCRTStartup()  Line 414	C
 	kernel32.dll!7c816fd7() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00610066() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	
 	d3dx9d_33.dll!00690057() 	



[Edited by - ankhd on March 2, 2008 11:16:20 PM]

Share this post


Link to post
Share on other sites
The interesting number here isn't 0x007363bf, but 0xfdfdfe1d. An astute observer will note a pattern -- it is very close to FDFDFDFD, and is off by a total of 0x10 -- e.g. 16, which is not only a multiple of common power of two numbers (e.g. 4, your 32-bit word size in bytes), but even is one itself.

This is one of many debug fill patterns, which Wikipedia tells us are guard bytes of a heap allocation, before and after it. In other words, you probably have a buffer overflow somewhere. You've failed to point out the exact line this error occurs on though.

Since it's trying to access this location, this means you must be using a pointer that has this debug value. V looks fine on the stack trace, so I suspect it to be the implicit "this" pointer of your Camera2 class, used to access it's members.

I suggest you post the source to SetupMatrices.

Edit: Also, recommended reading.

Share this post


Link to post
Share on other sites
Hi, Ive read all the info thanks its breaking here
SetupMatrices(void)
{
//set the cameras new position if we moved it
if(Camera)
{
// Update the view matrix representing the cameras
// new position/orientation.
Camera->getViewMatrix(&MatView);
//Device->SetTransform(D3DTS_VIEW, &MatView);
//FX
//LightTexEffect->SetMatrix(ViewMatrixHandle, &MatView);


}
the funny thing here is it will render once then on the second time around it will through the exception.
I but a break in the above function then steped into it
I will remove all thing but the camera class and see what happend.
Remember this only happens in debug

Share this post


Link to post
Share on other sites
Quote:
Original post by ankhd
SetupMatrices(void)

Looks fairly sane. Can I assume Camera is a member of MyAppWin? I'd also double check that Camera is indeed FDFDFDFD like I'm suspecting with your debugger.

This comment worries me:
Quote:
//set the cameras new position if we moved it
if(Camera) ...


Is there any place you're assigning it to something other than directly to null or a new statement? If not, the next two places I'm interested in are MyAppWin's constructor, and WinMain.

Quote:
Remember this only happens in debug

Right. As debug guards, your code is probably just silently overwriting memory in release mode, which creates the nastiest, hardest to track down type of bug. Good thing the problem is visible and repeatable in debug mode, eh?

Share this post


Link to post
Share on other sites
Cant find it I have stripped every thing out of the code but the carera and still does the same thing here is the classes
window class

class AppWin
{
public:

//---------------------------------------------------------------
// Functions to create, run, pause, and clean up the application
//---------------------------------------------------------------
AppWin(void);
//~AppWin(void){}
~AppWin(void);

void FreeD3D(void);
virtual HRESULT Create( HINSTANCE hInstance, TCHAR *classname, TCHAR *title, int width, int height);
virtual void Pause( bool bPause );
virtual void Release(void);//must call this
virtual void OnLostDevice(void){}
virtual void OnResetDevice(void){}
//--------------------------------------------------------------
//this returns true if the device is lost
//you can over ride it if you like
//---------------------------------------------------------------
virtual bool IsDeviceLost(void);


//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
virtual void Render(void);


//--------------------------------------------------------------------------------------
//check device caps for the current app
//-----------------------------------------------------------------------------------------
virtual bool CheckDeviceCaps(void)
{
return true;
}//end CheckDeviceCaps

//---------------------------------------------------------------------------------------
//this will start the time clock
//can pass TIMER_RESET to reset the clock
//---------------------------------------------------------------------------------------
void StartClock( TIMER_COMMAND command = TIMER_START);


//---------------------------------------------------------------------------------------
//this will calculate the frames per second so we can display the frame count later
//you must start the timer with DXUtil_Timer(TIMER_START);
//returns the elapsedtime
//---------------------------------------------------------------------------------------
FLOAT UpDateFrameCount(void);



//--------------------------------------------------------------------------------------
//this will return the frame rate in a string
//--------------------------------------------------------------------------------------
TCHAR *GetFrameRateStr(void){ return FrameStr;}


//--------------------------------------------------------------------------------------
//this will return the frame rate in a string
//--------------------------------------------------------------------------------------
TCHAR *GetElapsRateStr(void){ return FrameStrElaps;}



//--------------------------------------------------------------------------------------
//this will create the heading text if you want to use it
//--------------------------------------------------------------------------------------
bool InitHeading1(TCHAR *fontname,//name of the font to create
int height);//height of the text


//---------------------------------------------------------------------------------------
//call this if you want to use direct sound it will create a sound manager
// Create a static IDirectSound in the CSound class.
// Set coop level to DSSCL_PRIORITY, and set primary buffer
// format to stereo, 22kHz and 16-bit output.
//For example, to set the primary buffer format to 22kHz stereo, 16-bit
// then: dwPrimaryChannels = 2
// dwPrimaryFreq = 22050,
// dwPrimaryBitRate = 16
//---------------------------------------------------------------------------------------
bool IntSound(DWORD dwPrimaryChannels = 2,
DWORD dwPrimaryFreq = 22050,
DWORD dwPrimaryBitRate = 16,
DWORD flags = DSSCL_PRIORITY);



//------------------------------------------------------------------------------------
//this will return the multisample that this device can support
//we will start at D3DMULTISAMPLE_4_SAMPLES and work back wards if the card canmt support it
//-------------------------------------------------------------------------------------
void GetMultiSampleSupported(DWORD *pQualityLevels, D3DMULTISAMPLE_TYPE *type);




//-------------------------------------------------------
//public members
//--------------------------------------------------------
HWND Hwnd;//the windows handle
HINSTANCE Hinstance;//this class instance
TCHAR ClassName[CLASSNAMESIZE];//the name of this class needed so we can register this class and delete it


//sound stuff
CSoundManager *SoundManager;//if you dont want it don't create it

//direct 3d stuff
LPDIRECT3D9 D3D; // Used to create the D3DDevice
LPDIRECT3DDEVICE9 Device; // Our rendering device
D3DPRESENT_PARAMETERS D3DPresentPrams;

CD3DFont *FontHeading1;//standard font if using it will be set to NULL default

TCHAR FrameStr[FRAMESTR_SIZE];
TCHAR FrameStrElaps[FRAMESTR_SIZE];
int Width;
int Height;//window width and height
DWORD FrameCnt;//will count the frames

FLOAT FPS;//the frames per second

bool Windowed;//true if this is a window false for full screens
bool Use3D;//if we want to us d3d most times we will
};//end class
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////



CPP file

//---------------------------------------------------------------
// Functions to create, run, pause, and clean up the application
//---------------------------------------------------------------
AppWin::AppWin(void)
{
Hwnd = NULL;
Hinstance = NULL;
SoundManager = NULL;

D3D = NULL; // Used to create the D3DDevice
Device = NULL; // Our rendering device

Use3D = true;
Windowed = false;
FrameCnt = 0;
FPS = 0;
FontHeading1 = NULL;
strcpy_s(FrameStr, FRAMESTR_SIZE, "Frame Rate: 200");
strcpy_s(FrameStrElaps, FRAMESTR_SIZE, "Elaps: 200");

}//end
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////




//---------------------------------------------------------------
// Functions to
//---------------------------------------------------------------
AppWin::~AppWin(void)
{

}//end
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////



//---------------------------------------------------------------
// Functions to
//---------------------------------------------------------------
void AppWin::FreeD3D(void)
{
//MessageBox(Hwnd,"Releasing Main Window", "RELEASE()", MB_OK);
// When we done with a particular WNDCLASSEX, we can tell Windows we don't need
// it anymore and free up memory. That's what UnregisterClass() does. You'll notice
// we also pass the HINSTANCE of the window. Why do we do that? Well more than one
// window can use the same WNDCLASSEX, so UnregisterClass() will only completely
// remove the WNDCLASSEX if no windows are currently using it.
if(Hinstance)
UnregisterClass(ClassName, Hinstance);

Hinstance = NULL;
Hwnd = NULL;

if(FontHeading1)
{
FontHeading1->InvalidateDeviceObjects();
FontHeading1->DeleteDeviceObjects();
delete FontHeading1;
FontHeading1 = NULL;
}

//free the directx 3d stuff
SAFE_RELEASE(Device); // Our rendering device
SAFE_RELEASE(D3D); // Used to create the D3DDevice

//free sound
SAFE_DELETE(SoundManager);

// Cleanup COM
CoUninitialize();

}//end FreeD3D
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////






//---------------------------------------------------------------
// Functions to
//---------------------------------------------------------------
void AppWin::Release(void)
{
FreeD3D();

}//end Release
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////



//--------------------------------------------------------------------------------------
//this will create the heading text if you want to use it
//--------------------------------------------------------------------------------------
bool AppWin::InitHeading1(TCHAR *fontname,//name of the font to create
int height)//height of the text
{
if(Device == NULL)
{
MessageBox(Hwnd,"Failed To Create Text Heading 1", "Initialize Error(Device Object)", MB_OK);
return false;
}

// Create a font object and initialize it.
FontHeading1 = new CD3DFont(fontname, height, 0);
if(FontHeading1 == NULL)
{
MessageBox(Hwnd,"Failed To Create Text Heading 1", "Initialize Error(Font Create)", MB_OK);
return false;
}

FontHeading1->InitDeviceObjects(Device);
FontHeading1->RestoreDeviceObjects();
return true;//all ok
}//end
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////






//---------------------------------------------------------------------------------------
//this will start the time clock
//can pass TIMER_RESET to reset the clock
//---------------------------------------------------------------------------------------
void AppWin::StartClock(TIMER_COMMAND command)
{
FrameCnt++;
// Performs timer opertations. Use the following commands:
// TIMER_RESET - to reset the timer
// TIMER_START - to start the timer
// TIMER_STOP - to stop (or pause) the timer
// TIMER_ADVANCE - to advance the timer by 0.1 seconds
// TIMER_GETABSOLUTETIME - to get the absolute system time
// TIMER_GETAPPTIME - to get the current time
// TIMER_GETELAPSEDTIME - to get the time that elapsed between
// TIMER_GETELAPSEDTIME calls
DXUtil_Timer(command);// TIMER_COMMAND command )



}//end StartClock
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////



//---------------------------------------------------------------------------------------
//this will calculate the frames per second so we can display the frame count later
//you must start the timer with DXUtil_Timer(TIMER_START);
//returns the elapsed time
//---------------------------------------------------------------------------------------
FLOAT AppWin::UpDateFrameCount(void)
{
FrameCnt++;
// Performs timer opertations. Use the following commands:
// TIMER_RESET - to reset the timer
// TIMER_START - to start the timer
// TIMER_STOP - to stop (or pause) the timer
// TIMER_ADVANCE - to advance the timer by 0.1 seconds
// TIMER_GETABSOLUTETIME - to get the absolute system time
// TIMER_GETAPPTIME - to get the current time
// TIMER_GETELAPSEDTIME - to get the time that elapsed between
// TIMER_GETELAPSEDTIME calls
FLOAT timeElapsed = DXUtil_Timer(TIMER_GETELAPSEDTIME);// TIMER_COMMAND command )
static FLOAT te = timeElapsed;
//FPS = (FLOAT)FrameCnt / timeElapsed;

//sprintf_s(FrameStr, FRAMESTR_SIZE, "Frame Rate::%f Elapsed Time : %f", FPS, timeElapsed);

te+=timeElapsed;
if(te > 1.0f)//one second
{

FPS = (FLOAT)FrameCnt /te;//timeElapsed;
sprintf_s(FrameStr, FRAMESTR_SIZE, "Frame Rate::%f", FPS);//timeElapsed);
sprintf_s(FrameStrElaps, FRAMESTR_SIZE, "Elapsed Time : %f", te);//timeElapsed);

FrameCnt = 0;//reset the frames
//timeElapsed = te;
te = 0;
//DXUtil_Timer(TIMER_RESET);//reset the timer
}


return timeElapsed;
}//end UpDateFrameCount
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////








//---------------------------------------------------------------
// Functions to
//---------------------------------------------------------------
HRESULT AppWin::Create( HINSTANCE hInstance, TCHAR *classname, TCHAR *title, int width, int height)
{
HRESULT hr = S_OK;

/* INITCOMMONCONTROLSEX ct;
ct.dwSize = sizeof(ct);//Size of the structure, in bytes.
ct.dwICC = ICC_COOL_CLASSES;//ICC_STANDARD_CLASSES;//Set of bit flags that indicate which common control
//classes will be loaded from the DLL. This value can be a combination of the following:

InitCommonControlsEx( &ct); // LPINITCOMMONCONTROLSEX lpInitCtrls
*/


// Init COM so we can use CoCreateInstance
CoInitializeEx(NULL, COINIT_MULTITHREADED);


// Windows have two set of attributes that define how they work. The first is a WNDCLASSEX
WNDCLASSEX wndclass = {0};

// *** Begin filling the fields of the WNDCLASSEX ***

// Here we set the size of the wndclass. You will see this a lot in windows, it's kinda odd.
wndclass.cbSize = sizeof(wndclass);

// The style we want is vertical redraw and horizontal redraw. These styles say that if the window
wndclass.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;

// Here we assign our WndProc. Remember the WndProc is a function that will intercept and deal
// with any messages the operating system sends our window.
wndclass.lpfnWndProc = WndProc;


wndclass.hInstance = Hinstance = hInstance;


wndclass.hbrBackground = (HBRUSH)( COLOR_WINDOW+1 );//(HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.hIcon = LoadIcon( NULL, IDI_APPLICATION );

wndclass.hCursor = LoadCursor( NULL, IDC_ARROW );

//strcpy(ClassName,classname);
//wsprintf(ClassName, "%s", classname);
//lstrcpy(ClassName, classname);
hr = StringCchCopy(ClassName,// LPTSTR pszDest,
CLASSNAMESIZE,//size_t cchDest,
classname);//LPCTSTR pszSrc
if(FAILED(hr))
return hr;//error


wndclass.lpszClassName = ClassName;

RegisterClassEx(&wndclass);


int w = width;
int h = height;

if(Windowed == false)
{
//set the width and height to the screens
w = GetSystemMetrics(SM_CXSCREEN );//SM_CXFULLSCREEN);
h = GetSystemMetrics(SM_CYSCREEN);//);SM_CYFULLSCREEN
}

Width = w;
Height = h;
// Now we actually create the window. CreateWindowEx() returns a handle to the window, which we
Hwnd = CreateWindowEx(WS_EX_CONTROLPARENT | WS_EX_NOINHERITLAYOUT , ClassName, title, WS_OVERLAPPEDWINDOW ,
0,//CW_USEDEFAULT,
0,//CW_USEDEFAULT,
w, h, NULL, NULL, hInstance, NULL);

//this sets the window up so the mouse points are correct
RECT rcClient = {0, 0, w, h};
AdjustWindowRect( &rcClient, GetWindowLong( Hwnd, GWL_STYLE ), FALSE );
MoveWindow( Hwnd, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, TRUE );



// Now that the window is created, lets show it! The ShowWindow() function shows the
ShowWindow(Hwnd, TRUE);

// This tells the window to draw itself so we can see it
UpdateWindow(Hwnd);

//ok if we want to us d3d we load it here
if(Use3D == false)
return hr;//all ok should be s_ok

//ok create the d3d objects
// Create the D3D object, which is needed to create the D3DDevice.
if( NULL == (D3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
{
MessageBox(Hwnd,"Failed To Init D3D", "AppWin->Create()", MB_OK);
return E_FAIL;
}

// Set up the structure used to create the D3DDevice. Most parameters are
// zeroed out. We set Windowed to TRUE, since we want to do D3D in a
// window, and then set the SwapEffect to "discard", which is the most
// efficient method of presenting the back buffer to the display. And
// we request a back buffer format that matches the current desktop display
// format.
// D3DPRESENT_PARAMETERS D3DPresentPrams; moved as a member now
ZeroMemory( &D3DPresentPrams, sizeof(D3DPresentPrams) );

D3DPresentPrams.BackBufferWidth = Width;//,
D3DPresentPrams.BackBufferHeight = Height;

D3DPresentPrams.BackBufferFormat = D3DFMT_A8R8G8B8;//D3DFMT_UNKNOWN;//D3DFORMAT
D3DPresentPrams.BackBufferCount = 1;//UINT
// D3DPresentPrams.MultiSampleType = D3DMULTISAMPLE_4_SAMPLES;//D3DMULTISAMPLE_NONE;//D3DMULTISAMPLE_TYPE
// D3DPresentPrams.MultiSampleQuality = 1;//DWORD
D3DPresentPrams.SwapEffect = D3DSWAPEFFECT_DISCARD;//D3DSWAPEFFECT
D3DPresentPrams.hDeviceWindow = Hwnd;//HWND
D3DPresentPrams.Windowed = Windowed;//Windowed;//BOOL
//D3DPresentPrams.EnableAutoDepthStencil = true;//BOOL
//D3DPresentPrams.AutoDepthStencilFormat = D3DFMT_D16;//D3DFMT_UNKNOWN;//D3DFORMAT D3DFMT_D24S8;//
//D3DPresentPrams.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;//DWORD
//D3DPresentPrams.FullScreen_RefreshRateInHz = 0;//UINT
//D3DPresentPrams.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;//UINT

DWORD QualityLevels = 0;
D3DMULTISAMPLE_TYPE multisampletype = D3DMULTISAMPLE_NONE;

GetMultiSampleSupported(&QualityLevels, &multisampletype);

D3DPresentPrams.MultiSampleType = multisampletype;//D3DMULTISAMPLE_6_SAMPLES;//D3DMULTISAMPLE_4_SAMPLES ;//D3DMULTISAMPLE_NONE;
D3DPresentPrams.MultiSampleQuality = QualityLevels;

D3DPresentPrams.SwapEffect = D3DSWAPEFFECT_DISCARD;

//D3DPresentPrams.Windowed = windowed;
D3DPresentPrams.EnableAutoDepthStencil = true;
D3DPresentPrams.AutoDepthStencilFormat = D3DFMT_D24S8;
D3DPresentPrams.Flags = 0;//D3DPRESENTFLAG_DEVICECLIP | D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
D3DPresentPrams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
D3DPresentPrams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;


// Create the Direct3D device. Here we are using the default adapter (most
// systems only have one, unless they have multiple graphics hardware cards
// installed) and requesting the HAL (which is saying we want the hardware
// device rather than a software one). Software vertex processing is
// specified since we know it will work on all cards. On cards that support
// hardware vertex processing, though, we would see a big performance gain
// by specifying hardware vertex processing.
hr = D3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, Hwnd,
D3DCREATE_PUREDEVICE | D3DCREATE_HARDWARE_VERTEXPROCESSING,//D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&D3DPresentPrams, &Device);
if(FAILED(hr))
{
MessageBox(Hwnd,"Failed To Set D3DCREATE_PUREDEVICE Type\nWill now try D3DDEVTYPE_HAL Type", "AppWin->Create()", MB_OK);
hr = D3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, Hwnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&D3DPresentPrams, &Device);
if(FAILED(hr))
{
MessageBox(Hwnd,"Failed To Set D3DDEVTYPE_HAL Type\nWill now try D3DDEVTYPE_NULLREF Type", "AppWin->Create()", MB_OK);

hr = D3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, Hwnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&D3DPresentPrams, &Device);
if(FAILED(hr))
{
MessageBox(Hwnd,"Failed To Init D3DDEVTYPE_NULLREF Device Will Close now", "AppWin->Create()", MB_OK);
return E_FAIL;
}
}

}



// Device state would normally be set here
return hr;
}//end Create
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////








//---------------------------------------------------------------
// Functions to
//---------------------------------------------------------------
void AppWin::Pause( bool bPause )
{
}//end
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////







//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
void AppWin::Render(void)
{
if(NULL == Device)
return;

// Clear the backbuffer to a blue color
Device->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 );

// Begin the scene
if( SUCCEEDED(Device->BeginScene() ) )
{
// Rendering of scene objects can happen here

// End the scene
Device->EndScene();
}

// Present the backbuffer contents to the display
Device->Present( NULL, NULL, NULL, NULL );

}//end Render
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////











//---------------------------------------------------------------------------------------
//call this if you want to use direct sound it will create a sound manager
// Create a static IDirectSound in the CSound class.
// Set coop level to DSSCL_PRIORITY, and set primary buffer
// format to stereo, 22kHz and 16-bit output.
//For example, to set the primary buffer format to 22kHz stereo, 16-bit
//then: dwPrimaryChannels = 2
//dwPrimaryFreq = 22050,
//dwPrimaryBitRate = 16
//---------------------------------------------------------------------------------------
bool AppWin::IntSound(DWORD dwPrimaryChannels,
DWORD dwPrimaryFreq,
DWORD dwPrimaryBitRate,
DWORD flags)
{
// Create a static IDirectSound in the CSound class.
// Set coop level to DSSCL_PRIORITY, and set primary buffer
// format to stereo, 22kHz and 16-bit output.
SoundManager = new CSoundManager();
if(SoundManager == NULL)
{
MessageBox(Hwnd,"No Memory For SoundManager", "AppWin->IntSound()", MB_OK | MB_ICONERROR );
return false;
}

HRESULT hr;//DSSCL_PRIORITY
if(FAILED(hr = SoundManager->Initialize(Hwnd, flags ) ) )
{
MessageBox(Hwnd,"Failed SoundManager Initialize()", "AppWin->IntSound()", MB_OK | MB_ICONERROR );
return false;
}

if( FAILED(hr = SoundManager->SetPrimaryBufferFormat(dwPrimaryChannels, dwPrimaryFreq, dwPrimaryBitRate ) ) )
{
MessageBox(Hwnd,"Failed SoundManager SetPrimaryBufferFormat()", "AppWin->IntSound()", MB_OK | MB_ICONERROR );
return false;
}

return true;//all ok

}//end IntSound
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////




//------------------------------------------------------------------------------------
//this will return the multisample that this device can support
//we will start at D3DMULTISAMPLE_6_SAMPLES and work back wards if the card canmt support it
//-------------------------------------------------------------------------------------
void AppWin::GetMultiSampleSupported(DWORD *pQualityLevels, D3DMULTISAMPLE_TYPE *type)
{
HRESULT r1, r2;
DWORD QualityLevels = 0;

D3DMULTISAMPLE_TYPE types[6] = {D3DMULTISAMPLE_8_SAMPLES, D3DMULTISAMPLE_7_SAMPLES, D3DMULTISAMPLE_6_SAMPLES, D3DMULTISAMPLE_4_SAMPLES, D3DMULTISAMPLE_3_SAMPLES, D3DMULTISAMPLE_2_SAMPLES};

for(int ctr = 0; ctr < 6; ctr++)
{
QualityLevels = 0;
r1 = D3D->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, D3DFMT_A8R8G8B8,
FALSE, types[ctr], &QualityLevels);
if(SUCCEEDED(r1))
{
//QualityLevels = 0;
r2 = D3D->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, D3DFMT_D24S8,
FALSE, types[ctr], &QualityLevels);
if(SUCCEEDED(r2))
{
//we can use this sample so lets set it
*pQualityLevels = 0;//QualityLevels;
*type = types[ctr];
//TCHAR buff[MAX_PATH];
//sprintf_s(buff, MAX_PATH, "QualityLevels = %d, Sample Level = %d", QualityLevels, types[ctr]);
//MessageBox(Hwnd, buff, "AppWin::GetMultiSampleSupported()", MB_OK);
return;//where done
}//end found back buffer and stencil buffers multi sample types

}//end found a match

}//end all sample types

//we neaver set a type so set one
*pQualityLevels = 0;
*type = D3DMULTISAMPLE_NONE;

}//end GetMultiSampleSupported
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////








//--------------------------------------------------------------
//this returns true if the device is lost
//you can over ride it if you like
//---------------------------------------------------------------
bool AppWin::IsDeviceLost(void)
{
// Get the state of the graphics device.
HRESULT hr = Device->TestCooperativeLevel();

// If the device is lost and cannot be reset yet then
// sleep for a bit and we'll try again on the next
// message loop cycle.
if( hr == D3DERR_DEVICELOST )
{
Sleep(20);
return true;
}
// Driver error, exit.
else if( hr == D3DERR_DRIVERINTERNALERROR )
{
MessageBox(Hwnd, "Internal Driver Error...Exiting", 0, 0);
PostQuitMessage(0);
return true;
}
// The device is lost but we can reset and restore it.
else if( hr == D3DERR_DEVICENOTRESET )
{
OnLostDevice();
hr = Device->Reset(&D3DPresentPrams);
if(hr != D3D_OK)
return true;

OnResetDevice();
return false;
}
else
return false;
}//end IsDeviceLost
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////





Main.cpp

Camera2 *Camera = NULL;//(Window.Device);//needs a device


//cLensFlare LensFlare;

//CErrorReport ErrorReport;//manages a dialog box and is controlled by F3 key



//-----------------------------------------------------------
//drived window class for this app
//-----------------------------------------------------------
class MyAppWin : public AppWin
{
public:
MyAppWin(void):AppWin()
{
ObjectScale = 1.0f;



DisplayFrameRate = false;

m_dwNumIntersections = 0; // Number of faces intersected
m_pVB = NULL;
M_Terrain = NULL;
// m_Water = NULL;
// m_WaterDMap = NULL;
CameraToGround = false;





}
~MyAppWin(void)
{
}


//-----------------------------------------------------------------
//over ride release function
//-----------------------------------------------------------------
void Release(void);
void Render(void);

//------------------------------------------------------------------
//new functions for this class
//------------------------------------------------------------------
HRESULT InitVB(void);




//----------------------------------------------------------------------
//reset things for lost device
//----------------------------------------------------------------------
void OnLostDevice(void);

//----------------------------------------------------------------------
//reset things for lost device
//----------------------------------------------------------------------
void OnResetDevice(void);



//-----------------------------------------------------------------
//see if the device supports our needs
//-----------------------------------------------------------------
bool CheckDeviceCaps(void);




//-----------------------------------------------------------------------------
// Name: SetupMatrices()
// Desc: Sets up the world, view, and projection transform matrices.
//-----------------------------------------------------------------------------
void SetupMatrices(void);


//-----------------------------------------------------------------------------
// Name: SetupLights()
// Desc: Sets up the lights and materials for the scene.
//-----------------------------------------------------------------------------
void SetupLights(void);






//-----------------------------------------------------------------------------
// Name: Pick()
// Desc: Checks if mouse point hits geometry
// the scene.
//-----------------------------------------------------------------------------
HRESULT Pick(D3DXMATRIXA16 *transobj);




//-----------------------------------------------------------------
//Public Members
//-----------------------------------------------------------------
//CControlsRecources ControlResources;//this has all the textures for the edit boxs and other controls




DWORD m_dwNumIntersections; // Number of faces intersected
INTERSECTION m_IntersectionArray[MAX_INTERSECTIONS]; // Intersection info
LPDIRECT3DVERTEXBUFFER9 m_pVB; // VB for picked triangles

D3DVERTEXBUFFER_DESC VBDescription;//holds the description of the above vb


float ObjectScale;//the scale of all objects
bool DisplayFrameRate;
bool CameraToGround;//if true the camera is attached to the ground


Terrain *M_Terrain;//our terrain class

// Water *m_Water;//builds small water effects on a mesh
// WaterDMap *m_WaterDMap;//water with a displacement map

// Sky *m_SkyBox;

DirLight mLight;

//cQuadTree QuadTree;//our data storage class



};//end class
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////






RayMeshCollisionData RayMeshCol;

MyAppWin Window;//a class the managers the main window we need to make a
message pump for this but

Mouse AppMouse;//class for the mouse all apps will now use this



//CD3DArcBall ArcBall; // Mouse rotation utility











//-----------------------------------------------------------------------------------------------
// Here is our WndProc (Window Procedure). We'll send it messages
// we receive and have it deal with them.
//------------------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam);




//---------------------------------------------------------------------------------------
//this will load a mesh object with no animations
//----------------------------------------------------------------------------------------
void LoadMeshX(void);


//-----------------------------------------------------------------------------
//this will do collision for the columns
//-----------------------------------------------------------------------------
void intersect(D3DXMATRIXA16 *World);




//-------------------------------------------------------------------------------
// The main window function (equavilent to main() in a console application)
//-------------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)// Here is our "main()" for windows. We must have this for a windows application.
{


// MSG - A MeSsaGe variable to hold what messages are being sent to the window.
// For instance, if the window was clicked, closed, moved, etc...
MSG msg;



//set up the window
Window.Windowed = true;
Window.Use3D = true;
HRESULT hr = Window.Create(hInstance,//instance
"MAINWINDOWAPP2",//classname for reg
"Ankh Design Game's World Builder V1.0",//Title
800,//width ),//GetSystemMetrics(SM_CXFULLSCREEN)
600);//height ));//GetSystemMetrics(SM_CXFULLSCREEN)


if(FAILED(hr))
{
MessageBox(NULL,"ERROR", "APP FAILED", MB_OK);
return 0;
}

//set up the view port
ViewPort.Width = Window.Width;
ViewPort.Height = Window.Height;
ViewPort.X = 0;
ViewPort.Y = 0;
ViewPort.MaxZ = 1.0f;
ViewPort.MinZ = 0.0f;
hr = Window.Device->SetViewport(&ViewPort);

//Window.Device->GetViewport(&ViewPort);


//create the vb buffer for this app
hr = Window.InitVB();

if(hr != S_OK)
return 0;

Camera = new Camera2;// (Window.Device);//needs a device
if(Camera == NULL)
{
Window.Release();
return 0;
}


Camera->SetDefaults();

Camera->setCameraType(Camera2::AIRCRAFT);
D3DXVECTOR3 modelCentre(0.0f, 250.0f, 0.0f);
Camera->setPosition(&modelCentre);
//ok we need to set the cameras Projection pointer now
Camera->m_MatProj = &MatProj;


// Position the camera sensibly depending on the size of the model

float modelSphereRadius = 4.0f;



//VS
float angle = rand()%30;
//modelSphereRadius /= Window.ObjectScale;
D3DXVECTOR3 pos(0.0f,modelSphereRadius*2,-(modelSphereRadius*2));
//D3DXVECTOR3 pos( 3.0f, 4.0f,-20.0f );// -(modelSphereRadius ));
D3DXVECTOR3 look(0.0f, 0.0f, -1.0f);
//D3DXVec3Normalize(&look,&look);
// look.x = 0;
// look.y = 0;
// look.z = 0;

//
//D3DXVECTOR3 position( cosf(angle) * 7.0f, 5.0f, sinf(angle) * 7.0f );
// D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
// D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
//D3DXMATRIX V;
// D3DXMatrixLookAtLH(&MatView, &position, &target, &up);



//look = modelCentre - pos;
//Camera->setLook(&look);
//Camera->setPosition(&pos);


//Window.SetupLights();



Window.StartClock();

// All right! Finally our window is created and visible. Now it's time to
// have it do things. There are multiple ways to write what's referred to
// as the "window loop", but below is a typical way to go about it. Lets
// digest the window loop

while(1) // Loop forever
{
// PeekMessage() peeks at the operating systems message queue and returns true
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// If we receive a message, PeekMessage() will return true and will
// enter this portion of the code

// If the message says to quit, we quit and break out the while(1) loop
if(msg.message == WM_QUIT)
break;

// Translate message takes windows virtual key codes and translates
TranslateMessage(&msg);

// The DispatchMesage() function sends the message we recieved from PeekMessage()
// to the WndProc.
DispatchMessage(&msg);
}
else
{
if(!Window.IsDeviceLost())
Window.Render();
}
}



//Window.Release();//must call this

// Return the exit code for the application. This exit code was
// set by the PostQuitMessage() function that we call in the WndProc()
return (int)msg.wParam;
}//end win main
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////













//-----------------------------------------------------------------------------------------------
// Here is our WndProc (Window Procedure). We'll send it messages
// we receive and have it deal with them.
//------------------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{

// Pass mouse messages to the ArcBall so it can build internal matrices
//ArcBall.HandleMouseMessages( hwnd, Msg, wParam, lParam );

//Window.MenuManager.MessageHandler(Msg, wParam, lParam);

// ErrorReport.MessageHandler(Msg,wParam, lParam);
// This checks what the message is. Below is some of the message that windows might return.
// There of course are HUNDREDS of potential messages.
switch(Msg)
{
// The only message that you NEED to deal with, is the WM_DESTROY. The rest you don't have to check for.
// Below are just some examples on how to check for a message.

case WM_CREATE: // This message is sent when the window is created.
// We would want to put our initialization code here...



break;

case WM_SIZE: // This message happens when we resize the window.
// We would put code to resize text or a picture here...

break;

case WM_PAINT: // This message is sent to the WndProc when the window needs to be repainted.
{
//PAINTSTRUCT ps;
//HDC hdc = BeginPaint(hwnd, &ps);

//TextOut(hdc,200,10,"Hello World",11);

//EndPaint(hwnd, &ps);

//ValidateRect( hwnd, 0 );

}break;

// break;

case WM_DESTROY: // This message is sent when it's time to destroy the window.
{ // Here you would handle deinitialization, freeing memory, etc.

//
ReleaseCapture();

Window.Release();//must call this


// Cleanup COM
//CoUninitialize();

// If you look back up top at our window loop you notice a piece of code like this:
// if(msg.message == WM_QUIT)
// break;
// PostQuitMessage() sends the WM_QUIT message. The parameter we pass is
// the exit code we want to report to the operating system. By
// passing zero we're saying "Zero errors occured in the application."
PostQuitMessage(0);

}break;

/* case BUTTON_WINDOW_MSG:
{
int button = (int) wParam;
switch(button)
{
case 0:
{
MessageBox(Window.Hwnd,"Click Me","Message POST TEST",MB_OK);
}break;
}//end switch

}break;*/

case WM_KEYUP:
{
int key = (int) wParam;

//TCHAR buff[100];
//sprintf_s(buff, 100, "Key = %d,",key);
//MessageBox(hwnd, buff, "Key up", MB_OK);
/*
if( key == 48)//VK_NUMPAD1 )
Window.M_Terrain->SetLOD(50);
if(key == 49)//VK_NUMPAD2)
Window.M_Terrain->SetLOD(200);
if(key == 50)//VK_NUMPAD3 )
Window.M_Terrain->SetLOD(500);
if(key == 51)//VK_NUMPAD4 )
Window.M_Terrain->SetLOD(800);
if(key == 52)//VK_NUMPAD5 )
Window.M_Terrain->SetLOD(1024);
if(key == 53)//VK_NUMPAD6 )
Window.M_Terrain->SetLOD(1400);
if(key == 54)//VK_NUMPAD7 )
Window.M_Terrain->SetLOD(1600);
if(key == 55)//VK_NUMPAD8)
Window.M_Terrain->SetLOD(2000);
if(key == 56)//VK_NUMPAD9)
Window.M_Terrain->SetLOD(2048);*/

}break;

case WM_KEYDOWN:
{
int key = (int) wParam;
if(key == VK_RETURN)
{


MessageBox(Window.Hwnd,"test","Message Test",MB_OK);

}

if(key == VK_F1)
{

}

if(key == VK_F2)
{

// ErrorReport.ToggleDisplay();

}//end f2 key

if(key == VK_F3)
{ //toggle the frame rate display
if(Window.DisplayFrameRate)
Window.DisplayFrameRate = false;
else
Window.DisplayFrameRate = true;



}//end vk_f3

if(key == VK_F4)
{
if(Window.CameraToGround)
Window.CameraToGround = false;
else
Window.CameraToGround = true;
}//end f4 key



//Window.PlayerNamesDlg.ScrollControls(key);

/*float dist = 0.95f;
D3DXVECTOR3 dir(1,1,1);
switch(key)
{
case VK_UP:
{
//Camera1->MoveUp(dist);
Camera->walk(dist);
}break;
case VK_RIGHT :
{
Camera->strafe(dist);// MoveRight(dist);
}break;
case VK_DOWN:
{
Camera->walk(-dist);// MoveForward(-dist);
//Camera1->MoveUp(-dist);
}break;
case VK_LEFT:
{
Camera->strafe(-dist);// MoveRight(-dist);
//Camera1->RotateRight(42.0f);//MoveInDirection(dist, &dir);
}break;
//case :
//{
//}break;
//case :
//{
//}break;

}//end switch key
*/

}break;
case WM_COMMAND:
{
HWND h = (HWND)lParam;


}break;//end command
case WM_CHAR:
{
int key = (int) wParam;
if(key == VK_RETURN)
{
//MessageBox(hwnd,g_PortStr,"Message Test",MB_OK);
}


//Window.PlayerNamesDlg.KeyInput(key);



}break;
case WM_LBUTTONDOWN:
{
//SetCapture(hwnd);
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
AppMouse.LBDown = true;
AppMouse.LBDTime = timeGetTime();




}break;
case WM_RBUTTONDOWN:
{
//SetCapture(hwnd);
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);


//Window.PlayerNamesDlg.DialogRighClick();



}break;
case WM_LBUTTONDBLCLK:
{
//MessageBox(hwnd,"jtrh","Message Test",MB_OK);
//SetCapture(hwnd);
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
//Window.PlayerNamesDlg.DialogLeftDoubleClick(x,y);


}break;
case WM_LBUTTONUP:
{
AppMouse.CheckLBDown();



//ReleaseCapture();
}break;
case WM_MOUSEWHEEL:
{
//fwKeys = GET_KEYSTATE_WPARAM(wParam);
short zDelta = (short) HIWORD(wParam);//GET_WHEEL_DELTA_WPARAM(wParam);

//MessageBox(hwnd,"","Message Test",MB_OK);
//Window.PlayerNamesDlg.DialogMouseWheel(zDelta);


}break;
//case WM_NCMOUSEMOVE:
//{
// MessageBox(hwnd,"MOUSE MOVE ","WM_NCMOUSEMOVE",MB_OK);
//}break;
case WM_CAPTURECHANGED:
{
//MessageBox(hwnd,"MOUSE CAPTURE CHANGED","WM_CAPTURECHANGED",MB_OK);
}break;
case WM_MOUSEMOVE:
{
//SetCapture(hwnd);
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
float ang = 0.01f;

AppMouse.Update(wParam, lParam);

//Window.PlayerNamesDlg.DialogOnMouseMove(x, y);


/*if(Camera)
{

//see what way the mouse moved based on its last pos
if(AppMouse.MovedLeft)
Camera->pitch(ang);//RotateRight(ang);////MoveInDirection(dist, &dir);Roll(ang);//
else//if(AppMouse.MovedRight)
Camera->pitch(-ang);//RotateRight(-ang);//Roll(-ang);//MoveInDirection(dist, &dir);
if(AppMouse.MovedDown)
Camera->yaw(ang) ;//RotateDown(ang);//MoveInDirection(dist, &dir);
else//if(AppMouse.MovedUp)
Camera->yaw(-ang);//RotateDown(-ang);//MoveInDirection(dist, &dir);
}
*/

//ReleaseCapture();
}break;
/*case WM_SYSCOMMAND:
{// Prevent moving/sizing and power loss in fullscreen mode
switch( wParam )
{
case SC_MOVE:
case SC_SIZE:
case SC_MAXIMIZE:
case SC_KEYMENU:
case SC_MONITORPOWER:
{ if( false == Window.FullScreen )
return 1;
else
return DefWindowProc(hwnd, Msg, wParam, lParam);

}break;
}
}break;
*/

// So what if we get a message that we don't explicitly handle? This is where
// the default window procedure comes in. All messages we don't handle ourselves,
// should get sent to the DefWindowProc(). It will apply a default Windows behavior
// to the message. For example, lets say somebody clicks the 'X' in the upper-right
// hand corner of the window. We could handle that message ourselves and set a quit
// message to the window or we could simply let the default window procedure handle it
// for us.
//default:

//return DefWindowProc(hwnd, Msg, wParam, lParam);
}//end message

// Typically if you handle a message in the WndProc, you return zero.
return DefWindowProc(hwnd, Msg, wParam, lParam);

}//end winproc
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////











//-----------------------------------------------------------------------------
// Name: InitVB()
// Desc: Creates a vertex buffer and fills it with our vertices. The vertex
// buffer is basically just a chuck of memory that holds vertices. After
// creating it, we must Lock()/Unlock() it to fill it. For indices, D3D
// also uses index buffers. The special thing about vertex and index
// buffers is that they can be created in device memory, allowing some
// cards to process them in hardware, resulting in a dramatic
// performance gain.
//-----------------------------------------------------------------------------
HRESULT MyAppWin::InitVB(void)
{
// Create vertex and index buffers.
//
//
// Fill the buffers with the cube data.

mddDevice = Device;

HRESULT hr = E_FAIL;

DWORD Starttime = timeGetTime();

//create the debug out put dialog
// bool val = ErrorReport.InitErrorReport(Hwnd, Device);
// if(val == false)
{
// MessageBox(Hwnd,"Fail To IntErrorReport","InitVB",MB_OK);

// return E_FAIL;
}


//load all sounds
if(IntSound() == false)
{
MessageBox(Hwnd,"Fail To Set Sound Manager","InitVB",MB_OK);

return hr;
}



//check the caps
if(CheckDeviceCaps() == false)
{
MessageBox(Hwnd, "Caps Failed", "Checking Hardware Caps", MB_OK);
return E_FAIL;//error
}



float modelSphereRadius;




//
// Create geometry:
//


//Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
//Device->SetRenderState(D3DRS_ZENABLE, TRUE ); // Enable Z-Buffer (Depth Buffer)
//Device->SetRenderState(D3DRS_CULLMODE, TRUE); // Disable Backface Cullin

//ArcBall.Init();
//ArcBall.SetWindow( Window.Width, Window.Height, 0.05f );
//ArcBall.SetRadius(modelSphereRadius);//m_fObjectRadius );


//create text for this window
Window.InitHeading1("Times New Roman",//TCHAR *fontnamename of the font to create
16);//int heightheight of the text


FLOAT fAspect = (FLOAT)Window.Width / (FLOAT)Window.Height;
D3DXMatrixIdentity(&MatProj);
D3DXMatrixPerspectiveFovLH(&MatProj, D3DX_PI/4, fAspect, 1.0f, 100000.0f);
Device->SetTransform( D3DTS_PROJECTION, &MatProj );




//create our QuadTree
// RECT mapsize={0,0 ,512, 512};
// if(QuadTree.CreateTree(&mapsize, 32) == false)
// {
// MessageBox(Hwnd,"Fail To Greate QuadTree","InitVB",MB_OK);

// return E_FAIL;
// }




//we need to init our vertex class
InitAllVertexDeclarations(Device);


/* M_Terrain = new Terrain(Device,//LPDIRECT3DDEVICE9 Device,
513,//UINT vertRows,
513,//UINT vertCols,
20.0f,//float dx,//the distance between verteice
20.0f,// dz,
"HeightMaps\\coastMountain513.raw",//coastMountain1025.raw std::string heightmap,
"Textures\\grass.dds",//std::string tex0,
"Textures\\dirt.dds",//std::string tex1,
"Textures\\rock.dds",//std::string tex2,
"BlendMaps\\blend_hm17.jpg",//std::string blendMap,blend_coastal.dds
2.0f,//float heightScale,
-112.0f);//float yOffset);

*/

// if(M_Terrain->BuilQuadtreeAndLinkSubMeshes() == false)
// {
// MessageBox(Hwnd, "Failed To Create Terrain QuadTree", "Window->IntVB()", MB_OK);
// return E_FAIL;//error
// }


//D3DXVECTOR3 toSun(0.0f, 1.0f, 0.0f);
//D3DXVec3Normalize(&toSun, &toSun);
//M_Terrain->setDirToSunW(toSun);



/*

//--------------------------------------------------------------------
//create the skybox here grassenvmap1024.dds sky_box2.dds clouds1.dds
m_SkyBox = new Sky(Device, "EnvironmentMap\\SkyClear1024.dds",//the cube map
"Textures\\clouds.dds",//the cload map has alpha channels
80.0f);



mLight.dirW = D3DXVECTOR3(0.0f, -2.0f, -1.0f);
D3DXVec3Normalize(&mLight.dirW, &mLight.dirW);
mLight.ambient = D3DXCOLOR(0.3f, 0.3f, 0.3f, 1.0f);
mLight.diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
mLight.spec = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f);




//-----------------------------------------------------------------------
//create the water here
D3DXMATRIX waterWorld;
D3DXMatrixTranslation(&waterWorld, 0.0f, 5.2f, 0.0f);

Mtrl waterMtrl;
waterMtrl.ambient = D3DXCOLOR(0.26f, 1.0f, 0.8f, 0.90f);//(0.26f, 0.23f, 0.3f, 0.90f);
waterMtrl.diffuse = D3DXCOLOR(0.26f, 1.0f, 0.8f, 0.90f);//(0.26f, 0.23f, 0.3f, 0.90f);
waterMtrl.spec = 1.0f*WHITE;
waterMtrl.specPower = 164.0f;

Water::InitInfo waterInitInfo;
waterInitInfo.dirLight = mLight;
waterInitInfo.mtrl = waterMtrl;
waterInitInfo.vertRows = 128;
waterInitInfo.vertCols = 128;
waterInitInfo.dx = 100.0f;
waterInitInfo.dz = 100.0f;
waterInitInfo.waveMapFilename0 = "NormalMaps\\wave0.dds";
waterInitInfo.waveMapFilename1 = "NormalMaps\\wave1.dds";
waterInitInfo.waveMapVelocity0 = D3DXVECTOR2(0.05f, 0.08f);
waterInitInfo.waveMapVelocity1 = D3DXVECTOR2(-0.02f, 0.1f);
waterInitInfo.texScale = 16.0f;
waterInitInfo.toWorld = waterWorld;

m_Water = new Water(Device, waterInitInfo);
m_Water->setEnvMap(m_SkyBox->getEnvMap());




//setup water with displacement images
//D3DXMatrixIdentity(&waterWorld);
D3DXMatrixTranslation(&waterWorld, 0.0f, 0.0f, 0.0f);
Mtrl dwaterMtrl;
dwaterMtrl.ambient = D3DXCOLOR(0.4f, 0.4f, 0.7f, 0.1f);
dwaterMtrl.diffuse = D3DXCOLOR(0.4f, 0.4f, 0.7f, 1.0f);
dwaterMtrl.spec = 0.8f*WHITE;
dwaterMtrl.specPower = 128.0f;

WaterDMap::InitInfo dwaterInitInfo;
dwaterInitInfo.dirLight = mLight;
dwaterInitInfo.mtrl = dwaterMtrl;
dwaterInitInfo.fxFilename = "FX\\waterdmap.fx";
dwaterInitInfo.vertRows = 128;
dwaterInitInfo.vertCols = 128;
dwaterInitInfo.dx = 0.28f;
dwaterInitInfo.dz = 0.28f;
dwaterInitInfo.waveMapFilename0 = "NormalMaps\\waveA.dds";//normal map
dwaterInitInfo.waveMapFilename1 = "NormalMaps\\waveB.dds";//normal map
dwaterInitInfo.dmapFilename0 = "DisplacemantMaps\\waterdmap0.dds";//displacementmap
dwaterInitInfo.dmapFilename1 = "DisplacemantMaps\\waterdmap1.dds";//displacementmap
dwaterInitInfo.waveNMapVelocity0 = D3DXVECTOR2(0.05f, 0.07f);
dwaterInitInfo.waveNMapVelocity1 = D3DXVECTOR2(-0.01f, 0.13f);
dwaterInitInfo.waveDMapVelocity0 = D3DXVECTOR2(0.012f, 0.015f);
dwaterInitInfo.waveDMapVelocity1 = D3DXVECTOR2(0.014f, 0.05f);
dwaterInitInfo.scaleHeights = D3DXVECTOR2(0.7f, 1.1f);
dwaterInitInfo.texScale = 8.0f;
dwaterInitInfo.toWorld = waterWorld;

m_WaterDMap = new WaterDMap(Device, dwaterInitInfo);



//time the init process and say how long it takes
float ct = timeGetTime();
ct = ((ct - Starttime)/1000)/60;//minutes
TCHAR buff[MAX_PATH];
sprintf_s(buff, MAX_PATH, "Initialize Time = %f m", ct);

ErrorReport.AddErrorMessage(buff, false);



val = LensFlare.create(Device,"Textures\\lens_flare.dds");
if(val == false)
{
MessageBox(Hwnd, "Lens Flare Failed", "IntVb", MB_OK);
return E_FAIL;//error
}
*/


return S_OK;
}//end
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////






//-----------------------------------------------------------------
//see if the device supports our needs
//-----------------------------------------------------------------
bool MyAppWin::CheckDeviceCaps(void)
{
D3DCAPS9 caps;
(Device->GetDeviceCaps(&caps));

// Check for vertex shader version 3.0 support.
if( caps.VertexShaderVersion < D3DVS_VERSION(2, 0) )
{
MessageBox(Hwnd, "No Vertex Shader 2", "Checking Hardware Caps", MB_OK);
return false;
}

// Check for pixel shader version 3.0 support.
if( caps.PixelShaderVersion < D3DPS_VERSION(2, 0) )
{
MessageBox(Hwnd, "No Pixel Shader 2", "Checking Hardware Caps", MB_OK);
return false;
}

return true;
}//end checkDeviceCaps
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////




//-----------------------------------------------------------------
//over ride release function
//-----------------------------------------------------------------
void MyAppWin::Release(void)
{
//MessageBox(NULL,"OverRide Release()","Message Test",MB_OK);



if(Camera)
delete Camera;
Camera = NULL;


//free all elements of our tree
//QuadTree.DeleteTree();




SAFE_DELETE(M_Terrain);
// SAFE_DELETE(m_Water);
// SAFE_DELETE(m_WaterDMap);
// SAFE_DELETE(m_SkyBox);


//Effect->Release();
SAFE_RELEASE(m_pVB);

//SAFE_DELETE(PTerrain);

//Network.CleanupDirectPlay();

DestroyAllVertexDeclarations();

//frees the d3d interface and the device9 object
FreeD3D();
}//end Release
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////








//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
void MyAppWin::Render(void)
{
// Clear the backbuffer to a blue color
if(Device == NULL )
return;

D3DXMATRIXA16 all;
//position the sphere
D3DXMatrixTranslation(&all, 0.0f, 0.0f, 0.0f);


//all = trans; //(scale* (Rx * Ry))*






//if sky box we dont need the
Device->Clear( 0, NULL, D3DCLEAR_TARGET |D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL,
D3DCOLOR_XRGB(128,128,128), 1.0f, 0 );
//Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );




// Begin the scene
if( SUCCEEDED(Device->BeginScene()))
{


//static float t = timeGetTime();
//float currTime = (float)timeGetTime();
//float timeDelta = (currTime - t)*0.005f;

// Performs timer opertations. Use the following commands:
// TIMER_RESET - to reset the timer
// TIMER_START - to start the timer
// TIMER_STOP - to stop (or pause) the timer
// TIMER_ADVANCE - to advance the timer by 0.1 seconds
// TIMER_GETABSOLUTETIME - to get the absolute system time
// TIMER_GETAPPTIME - to get the current time
// TIMER_GETELAPSEDTIME - to get the time that elapsed between
// TIMER_GETELAPSEDTIME calls
//-----------------------------------------------------------------------------


FLOAT timeDelta = Window.UpDateFrameCount();//DXUtil_Timer(TIMER_GETELAPSEDTIME);// TIMER_COMMAND command )

static int frame = 0;





D3DXMATRIXA16 Rx, Ry, Rr, trans, gate ,Sx, Sy, Sr;
D3DXMATRIXA16 scale;

D3DXMatrixIdentity(&gate);
D3DXMatrixIdentity(&all);
D3DXMatrixIdentity(&trans);
D3DXMatrixIdentity(&Rx);

D3DXMatrixIdentity(&scale);
// rotate 45 degrees on x-axis

D3DXMatrixRotationY(&Ry, timeGetTime()* (2.0f * D3DX_PI) / 10000.0f);
D3DXMatrixRotationX(&Rx, D3DXToRadian(0));//timeGetTime()* (2.0f * D3DX_PI) / 10000.0f);



D3DXMatrixTranslation(&trans, 0.0f,-21.0f, 0.0f);


D3DXMatrixScaling(&scale,
Window.ObjectScale,
Window.ObjectScale,
Window.ObjectScale); //Rx


MatWorld = all = scale * trans;


//mess with the mesh head
D3DXMATRIX hr;
D3DXMatrixRotationY(&hr, timeGetTime()* (2.0f * D3DX_PI) / 1000.0f);
//XFileObjBiped.SetBoneMember(10,G_ArmTranPtr);
//G_ArmTranPtr,hr;








//tm+=5;
float Speed = 180;
float Speed1 = 180;

if( GetAsyncKeyState('W') & 0x8000f )
Camera->walk(Speed1 * timeDelta);

if( GetAsyncKeyState('S') & 0x8000f )
Camera->walk(-Speed1 * timeDelta);

if( GetAsyncKeyState('A') & 0x8000f )
Camera->strafe(-Speed1 * timeDelta);

if( GetAsyncKeyState('D') & 0x8000f )
Camera->strafe(Speed1 * timeDelta);

if( GetAsyncKeyState('R') & 0x8000f )
Camera->fly(Speed * timeDelta);

if( GetAsyncKeyState('F') & 0x8000f )
Camera->fly(-Speed * timeDelta);

if( GetAsyncKeyState('J') & 0x8000f )
{

//XFileObjBiped.AnimateSlower();




}

if( GetAsyncKeyState('K') & 0x8000f )
{
//XFileObjBiped.AnimateFaster();
//XFileObjBiped.NextAnimation();



}






/*
if(AppMouse.MovedUp)
Camera->pitch(0.2f * timeDelta);//RotateRight(ang);////MoveInDirection(dist, &dir);Roll(ang);//

if(AppMouse.MovedDown)
Camera->pitch(-0.2f * timeDelta);//RotateRight(-ang);//Roll(-ang);//MoveInDirection(dist, &dir);

if(AppMouse.MovedLeft)
Camera->yaw(0.8f * timeDelta) ;//RotateDown(ang);//MoveInDirection(dist, &dir);

if(AppMouse.MovedRight)
Camera->yaw(-0.8f * timeDelta);//RotateDown(-ang);//MoveInDirection(dist, &dir);
*/


if( GetAsyncKeyState(VK_UP) & 0x8000f )
Camera->pitch(1.0f * timeDelta);

if( GetAsyncKeyState(VK_DOWN) & 0x8000f )
Camera->pitch(-1.0f * timeDelta);

if( GetAsyncKeyState(VK_LEFT) & 0x8000f )
Camera->yaw(-1.0f * timeDelta);

if( GetAsyncKeyState(VK_RIGHT) & 0x8000f )
Camera->yaw(1.0f * timeDelta);

if( GetAsyncKeyState('N') & 0x8000f )
{
Camera->setCameraType(Camera2::AIRCRAFT);
Camera->roll(1.0f * timeDelta);
Camera->setCameraType(Camera2::LANDOBJECT);
}

if( GetAsyncKeyState('M') & 0x8000f )
{
Camera->setCameraType(Camera2::AIRCRAFT);
Camera->roll(-1.0f * timeDelta);
Camera->setCameraType(Camera2::LANDOBJECT);
}







D3DXMATRIXA16 wvp;


//we want the camera to stay on the ground
if(M_Terrain != NULL && CameraToGround)
{
D3DXVECTOR3 newPos;
D3DXVECTOR3 OldPos;
float offsetHeight = 52;
Camera->getPosition(&newPos);
OldPos = newPos;

// New position might not be on terrain, so project the
// point onto the terrain.
newPos.y = M_Terrain->getHeight(newPos.x, newPos.z) + offsetHeight;

// Now the difference of the new position and old (current)
// position approximates a tangent vector on the terrain.
D3DXVECTOR3 tangent = newPos - OldPos;
D3DXVec3Normalize(&tangent, &tangent);

// Now move camera along tangent vector.
newPos += tangent*Speed1 * timeDelta;

// After update, there may be errors in the camera height since our
// tangent is only an approximation. So force camera to correct height,
// and offset by the specified amount so that camera does not sit
// exactly on terrain, but instead, slightly above it.
newPos.y = M_Terrain->getHeight(newPos.x, newPos.z) + offsetHeight;
Camera->setPosition(&newPos);
}//end fixed to map


SetupMatrices();//we get the view matrix here

//D3DXMATRIXA16 ViewProj = MatView * MatProj ;

//G_ArmTranPtr->_12 =1.0f;// Speed * timeDelta;
//G_ArmTranPtr->_13 = 1.2f;
//G_ArmTranPtr->_14 = 1.0f;

D3DXMATRIXA16 ViewProj = MatView * MatProj ;

//if(m_SkyBox)
// m_SkyBox->draw(&ViewProj);

if(M_Terrain)
{




Device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);


//Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
M_Terrain->draw(&ViewProj);


//Device->SetRenderState(D3DRS_FILLMODE,D3DFILL_SOLID);
}




//render the water
//if(m_Water)
{
//m_Water->update(timeDelta);
//m_Water->draw(&ViewProj);
}

// if(m_WaterDMap)
{
// m_WaterDMap->update(timeDelta);
// m_WaterDMap->draw(&ViewProj);
}

// If a triangle is picked, draw it
if(RayMeshCol.m_dwNumIntersections > 0 )
{

}

D3DXVECTOR3 toSun(0.0f, 10.0f, 10.0f);
//D3DXVec3Normalize(&toSun, &toSun);

// World matrix is identity.
D3DXMATRIX W;
(Device->SetTransform(D3DTS_WORLD, &W));
//(Device->SetTransform(D3DTS_VIEW, &mView));
//H(Device->SetTransform(D3DTS_PROJECTION, &mProj));

//draw and update the lens flare ViewProj
// LensFlare.update(&MatView, toSun);

// LensFlare.render(Device);


//we need to see if its our turn
if(AppMouse.LeftClick)
{
AppMouse.LeftClick = false;
}

AppMouse.ResetFlags();


//FX



static TCHAR camloc[MAX_PATH];


if(Window.DisplayFrameRate)
{
TCHAR *fpss = Window.GetFrameRateStr();
TCHAR *elaps = Window.GetElapsRateStr();
//draw the windows frame rate with the default font heading1
Window.FontHeading1->DrawText(Width - 260, 45, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), fpss);
Window.FontHeading1->DrawText(Width - 260, 68, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), elaps);
}



//TCHAR camloc[1256];
D3DXVECTOR3 pos;
Camera->getPosition(&pos);

sprintf_s(camloc, 1256, "Camera::Location::X = %f Y = %f Z = %f",pos.x, pos.y, pos.z);
Window.FontHeading1->DrawText(20, 60, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f), camloc);


/* sprintf_s(camloc, 1256, "Ray Direction::X = %f Y = %f Z = %f",rayDir.x, rayDir.y, rayDir.z);
Window.FontHeading1->DrawText(20, 120, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f), camloc);

sprintf_s(camloc, 1256, "Ray Origin::X = %f Y = %f Z = %f",rayOrigin.x, rayOrigin.y, rayOrigin.z);
Window.FontHeading1->DrawText(20, 140, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f), camloc);


sprintf_s(camloc, 1256, "ViewPort W = %d H = %d \nMax Z = %f Min Z = %f,\n X = %f Y = %f",ViewPort.Width, ViewPort.Height, ViewPort.MaxZ,
ViewPort.MaxZ, ViewPort.MinZ, ViewPort.X, ViewPort.Y);
Window.FontHeading1->DrawText(20, 160, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f), camloc);



sprintf_s(camloc, 1256, "Selected Triangle Location X = %f, Y = %f, Z = %f", SlectedTri.x, SlectedTri.y , SlectedTri.z);
Window.FontHeading1->DrawText(20, 220, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f), camloc);


DWORD pAttribTableSize;
Window.XFileConnectBody.GetMeshPtr()-> GetAttributeTable(NULL,//D3DXATTRIBUTERANGE *pAttribTable,
&pAttribTableSize);

sprintf_s(camloc, 1256, "AttributeTable Size = %d", pAttribTableSize);
Window.FontHeading1->DrawText(20, 240, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f), camloc);

*/

//print the name of the selected mesh
//sprintf_s(camloc, 1256, "Selected Mesh Name = %s", RayMeshCol.MeshName);
//Window.FontHeading1->DrawText(20, 45, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f), camloc);

//sprintf_s(camloc, 1256, "Press F1 for Menu", RayMeshCol.MeshName);
Window.FontHeading1->DrawText(Width - 260, 5, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), "Press F3 for FrameRate");
Window.FontHeading1->DrawText(Width - 260, 25, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), "Press F2 for Debug List");




//error report has top view for now
// ErrorReport.Render();

// End the scene
Device->EndScene();

}//end beginscene

// Present the backbuffer contents to the display
Device->Present( NULL, NULL, NULL, NULL );





}//end Render
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////








//-----------------------------------------------------------------------------
// Name: SetupMatrices()
// Desc: Sets up the world, view, and projection transform matrices.
//-----------------------------------------------------------------------------
void MyAppWin::SetupMatrices(void)
{
if(Camera)
{
// Update the view matrix representing the cameras
// new position/orientation.
Camera->getViewMatrix(&MatView);

}


}//end SetMatrix
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////








//-----------------------------------------------------------------------------
// Name: SetupLights()
// Desc: Sets up the lights and materials for the scene.
//-----------------------------------------------------------------------------
void MyAppWin::SetupLights(void)
{
return;//not using any now vertex and pixel shaders do it
//Device->SetRenderState( D3DRS_LIGHTING, FALSE );
// Create a light
D3DLIGHT9 light;
ZeroMemory( &light, sizeof(D3DLIGHT9) );

float val = 1.0f;
//if(GameControl.Active == false)
// val = 0.3f;

light.Type = D3DLIGHT_DIRECTIONAL;
light.Diffuse.r = val;
light.Diffuse.g = val;
light.Diffuse.b = val;
light.Diffuse.a = val;

light.Specular.r = 1.0f;
light.Specular.g = 1.0f;
light.Specular.b = 1.0f;
light.Specular.a = 1.0f;


light.Range = 1000.0f;
light.Falloff = 1;
light.Attenuation0 = 0;
light.Attenuation1 = 1;
light.Attenuation2 = 0;




// Direction for our light - it must be normalized - pointing down and along z
D3DXVECTOR3 vecDir;
vecDir = D3DXVECTOR3(1.0f,-1.0f,280.5f);
D3DXVec3Normalize((D3DXVECTOR3*)&light.Direction, &vecDir );

// Turn light on
Device->SetLight( 0, &light );
Device->LightEnable( 0, TRUE );
Device->SetRenderState( D3DRS_LIGHTING, TRUE );
Device->SetRenderState( D3DRS_AMBIENT, 0x00202020 );
//Device->SetRenderState( D3DRS_DITHERENABLE, TRUE );
Device->SetRenderState( D3DRS_SPECULARENABLE, TRUE );
Device->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);
Device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
//Device->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_1WEIGHTS );

//Device->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);


//Device->SetRenderState( D3DRS_ZENABLE, TRUE );
}//end SetupLights
///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////








//-----------------------------------------------------------------------------
// Name: Pick()
// Desc: Checks if mouse point hits geometry
// the scene.
//-----------------------------------------------------------------------------
HRESULT MyAppWin::Pick(D3DXMATRIXA16 *transobj)
{
HRESULT hr = E_FAIL;
//D3DXVECTOR3 rayDir;
//D3DXVECTOR3 rayOrigin;

//reset the vas for the collisions
strcpy_s(RayMeshCol.MeshName,"NONE");
RayMeshCol.bHit = FALSE;
RayMeshCol.m_dwNumIntersections = 0;

//if(GetCapture() == NULL)
// return hr;//no mouse

if(AppMouse.LeftClick == false)
return hr;

POINT ptCursor = {AppMouse.LastX, AppMouse.LastY};
GetCursorPos(&ptCursor );
ScreenToClient(Hwnd, &ptCursor);

RayMeshCol.m_pVB = m_pVB;//need to set this so we can get the selected triangles


//D3DXMATRIXA16 m;
//D3DXMatrixInverse(&m, NULL,&matView);



////////////////////////////////TEST////////////////////////////////////////
//BOOL val = XFileGate.PickMesh(&RayMeshCol,//RayMeshCollisionData *rmc,//will hold valid data if this returns true
// ptCursor.x, ptCursor.y,//the mouse x y location
// &ViewPort,//CONST D3DVIEWPORT9 *ViewPort,
// &matProj,//CONST D3DXMATRIX *matProj,
// &matView,//CONST D3DXMATRIX *matView,
// transobj);//CONST D3DXMATRIX *pWorld)


return hr;
}//end Pick
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////





//----------------------------------------------------------------------
//reset things for lost device
//----------------------------------------------------------------------
void MyAppWin::OnLostDevice(void)
{

}//end OnLostDevice
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////



//----------------------------------------------------------------------
//reset things for lost device
//----------------------------------------------------------------------
void MyAppWin::OnResetDevice(void)
{

}//end OnResetDevice
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////



Share this post


Link to post
Share on other sites
Ok silly me look what I did
In the render loop I had some diplay text
static TCHAR msg[MAX_PATH]

down in the code mess(this is why you need to write clean code Keep telling myself that) any how
there is this line
sprintf_s(camloc, 1256, "Camera::Location::X = %f Y = %f Z = %f",pos.x, pos.y, pos.z);
Window.FontHeading1->DrawText(20, 60, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f), camloc);

take note of the 1256 drrrrrrr me should be MAX_PATH and the funny thing is I remember doing this 3 moth back huh.

I found it when I checked all of the code and there was just this last one so I removed the static key word and bingo this message came up

Run-Time Check Failure #2 - Stack around the variable 'camloc' was corrupted.
and the call stack for it

sorry for waiting all your time
cost me 5 hours

Share this post


Link to post
Share on other sites

This topic is 3574 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this