Skip to main content
gamedev.net
🔒 Locked

Member function causing access violations.

Started by Lois Desplat 6 replies 550+ views
Original Post
Lois Desplat
Lois Desplat
Hello, I am new at coding graphical applications, and thanks to Nehe I have been trying to learn openGL. Now the following code will be of the creation of a window in windows using openGL but I did not post on the openGL forum because it looks like it is not an openGL problem but more of my own ignorance of using C++ classes. I will post the bugs that msvc6.0 got me in debug mode after the code. - system_core.h -
      
#ifndef _SYSTEM_CORE_H_
#define _SYSTEM_CORE_H_

class cApplication
{
private:
   HINSTANCE   hInstance;     // Holds The Instance Of The Application

   HWND        hWnd;          // Holds Our Window Handle

   HDC         hDC;           // Private GDI Device Context

   HGLRC       hRC;           // Permanent Rendering Context


protected:
   char m_Class[MAX_PATH];    // Class name

   char m_Caption[MAX_PATH];  // Window caption


   GLuint PixelFormat;        // Holds The Results After Searching For A Match

   WNDCLASS wc;               // Windows Class Structure

   DWORD dwExStyle;           // Window Extended Style

   DWORD dwStyle;             // Window Style 

   
   RECT WindowRect;           // Grabs Rectangle Upper Left / Lower Right Values


public:

   bool keys[256];            // Array Used For The Keyboard Routine

   bool active;               // Window Active Flag Set To TRUE By Default

   bool fullscreen;           // Fullscreen Flag Set To Fullscreen Mode By Default


   cApplication();            // Constructor


   HWND        GethWnd();     // Returns window handle

   HINSTANCE   GethInst();    // Returns instance handle

   HDC         GethDC();      // Returns GDI Device Context

   HGLRC       GethRC();      // Returns Rendering Context


   GLvoid ReSizeGLScene(GLsizei width, GLsizei height);     // Resize and Initialize the GL Window

   BOOL CreateGLWindow(char *title, int width, int height, int bits, bool fullscreenflag);

   int InitGL(GLvoid);        // All setup for OpenGL goes here

   int DrawGLScene(GLvoid);   // Here's where we do all the drawing

   GLvoid KillGLWindow(GLvoid); // Properly kill the window


   BOOL Run();

   friend LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
};

static cApplication *g_pApp = NULL;

#endif
  

 - sytem_core.cpp -
      
#include "StdAfx.h"

cApplication::cApplication()
{
   g_pApp=this;
   // Initializing the variables

   g_pApp->hDC=NULL;
   g_pApp->hRC=NULL;
   g_pApp->hWnd=NULL;
   g_pApp->active=TRUE;
   g_pApp->fullscreen=TRUE;
}

HWND cApplication::GethWnd()
{
  return hWnd;
}

HINSTANCE cApplication::GethInst()
{
  return hInstance;
}

HDC cApplication::GethDC()
{
   return hDC;
}

HGLRC cApplication::GethRC()
{
   return hRC;
}

GLvoid cApplication::ReSizeGLScene(GLsizei width, GLsizei height)		// Resize And Initialize The GL Window

{
	if (height==0)										// Prevent A Divide By Zero By

	{
		height=1;										// Making Height Equal One

	}

	glViewport(0,0,width,height);						// Reset The Current Viewport


	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix

	glLoadIdentity();									// Reset The Projection Matrix


	// Calculate The Aspect Ratio Of The Window

	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix

	glLoadIdentity();									// Reset The Modelview Matrix

}

int cApplication::InitGL(GLvoid)										// All Setup For OpenGL Goes Here

{
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading

	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background

	glClearDepth(1.0f);									// Depth Buffer Setup

	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing

	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do

	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations

	return TRUE;										// Initialization Went OK

}

int cApplication::DrawGLScene(GLvoid)									// Here's Where We Do All The Drawing

{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear Screen And Depth Buffer

	glLoadIdentity();									// Reset The Current Modelview Matrix

	return TRUE;										// Everything Went OK

}

GLvoid cApplication::KillGLWindow(GLvoid)								// Properly Kill The Window

{
	if (fullscreen)										// Are We In Fullscreen Mode?

	{
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop

		ShowCursor(TRUE);								// Show Mouse Pointer

	}

	if (hRC)											// Do We Have A Rendering Context?

	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?

		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?

		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;										// Set RC To NULL

	}

	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC

	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;										// Set DC To NULL

	}

	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?

	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL

	}

	if (!UnregisterClass("OpenGL",hInstance))			// Are We Able To Unregister Class

	{
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;									// Set hInstance To NULL

	}
}

BOOL cApplication::CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
	WindowRect.left=(long)0;			// Set Left Value To 0

	WindowRect.right=(long)width;		// Set Right Value To Requested Width

	WindowRect.top=(long)0;				// Set Top Value To 0

	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height


	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag


	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window

	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.

	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages

	wc.cbClsExtra		= 0;									// No Extra Window Data

	wc.cbWndExtra		= 0;									// No Extra Window Data

	wc.hInstance		= hInstance;							// Set The Instance

	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon

	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer

	wc.hbrBackground	= NULL;									// No Background Required For GL

	wc.lpszMenuName		= NULL;									// We Don't Want A Menu

	wc.lpszClassName	= "OpenGL";								// Set The Class Name


	if (!RegisterClass(&wc))									// Attempt To Register The Window Class

	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE

	}
	
	if (fullscreen)												// Attempt Fullscreen Mode?

	{
		DEVMODE dmScreenSettings;								// Device Mode

		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared

		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure

		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width

		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height

		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel

		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.

		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.

			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				fullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE

			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.

				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE

			}
		}
	}

	if (fullscreen)												// Are We Still In Fullscreen Mode?

	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style

		dwStyle=WS_POPUP;										// Windows Style

		ShowCursor(FALSE);										// Hide Mouse Pointer

	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style

		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style

	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size


	// Create The Window

	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window

								"OpenGL",							// Class Name

								title,								// Window Title

								dwStyle |							// Defined Window Style

								WS_CLIPSIBLINGS |					// Required Window Style

								WS_CLIPCHILDREN,					// Required Window Style

								0, 0,								// Window Position

								WindowRect.right-WindowRect.left,	// Calculate Window Width

								WindowRect.bottom-WindowRect.top,	// Calculate Window Height

								NULL,								// No Parent Window

								NULL,								// No Menu

								hInstance,							// Instance

								NULL)))								// Dont Pass Anything To WM_CREATE

	{
		KillGLWindow();								// Reset The Display

		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE

	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be

	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor

		1,											// Version Number

		PFD_DRAW_TO_WINDOW |						// Format Must Support Window

		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL

		PFD_DOUBLEBUFFER,							// Must Support Double Buffering

		PFD_TYPE_RGBA,								// Request An RGBA Format

		bits,										// Select Our Color Depth

		0, 0, 0, 0, 0, 0,							// Color Bits Ignored

		0,											// No Alpha Buffer

		0,											// Shift Bit Ignored

		0,											// No Accumulation Buffer

		0, 0, 0, 0,									// Accumulation Bits Ignored

		16,											// 16Bit Z-Buffer (Depth Buffer)  

		0,											// No Stencil Buffer

		0,											// No Auxiliary Buffer

		PFD_MAIN_PLANE,								// Main Drawing Layer

		0,											// Reserved

		0, 0, 0										// Layer Masks Ignored

	};
	
	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?

	{
		KillGLWindow();								// Reset The Display

		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE

	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?

	{
		KillGLWindow();								// Reset The Display

		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE

	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?

	{
		KillGLWindow();								// Reset The Display

		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE

	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?

	{
		KillGLWindow();								// Reset The Display

		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE

	}

	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context

	{
		KillGLWindow();								// Reset The Display

		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE

	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window

	SetForegroundWindow(hWnd);						// Slightly Higher Priority

	SetFocus(hWnd);									// Sets Keyboard Focus To The Window

	ReSizeGLScene(width, height);					// Set Up Our Perspective GL Screen


	if (!InitGL())									// Initialize Our Newly Created GL Window

	{
      KillGLWindow();								// Reset The Display

		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE

   }

	return TRUE;									// Success

}

BOOL cApplication::Run()
{
   MSG		msg;									// Windows Message Structure

	BOOL	done=FALSE;								// Bool Variable To Exit Loop

   BOOL fscreen=TRUE;                     // added fscreen because otherwize it would go past this point

                                          // of course now CreateGLWindow is affected and it cannot evaluate

                                          // any statement.


	// Ask The User Which Screen Mode They Prefer

	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fscreen=FALSE;							// Windowed Mode

	}

	// Create Our OpenGL Window

	if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fscreen))
	{
		return 0;									// Quit If Window Was Not Created

	}

	while(!done)									// Loop That Runs While done=FALSE

	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?

		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?

			{
				done=TRUE;							// If So done=TRUE

			}
			else									// If Not, Deal With Window Messages

			{
				TranslateMessage(&msg);				// Translate The Message

				DispatchMessage(&msg);				// Dispatch The Message

			}
		}
		else										// If There Are No Messages

		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()

			if (active)								// Program Active?

			{
				if (keys[VK_ESCAPE])				// Was ESC Pressed?

				{
					done=TRUE;						// ESC Signalled A Quit

				}
				else								// Not Time To Quit, Update Screen

				{
					DrawGLScene();					// Draw The Scene

					SwapBuffers(hDC);				// Swap Buffers (Double Buffering)

				}
			}

			if (keys[VK_F1])						// Is F1 Being Pressed?

			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE

				KillGLWindow();						// Kill Our Current Window

				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode

				// Recreate Our OpenGL Window

				if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created

				}
			}
		}
	}

	// Shutdown

	KillGLWindow();									// Kill The Window

	return TRUE;
}


LRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window

							UINT	uMsg,			// Message For This Window

							WPARAM	wParam,			// Additional Message Information

							LPARAM	lParam)			// Additional Message Information

{
	switch (uMsg)									// Check For Windows Messages

	{
		case WM_ACTIVATE:							// Watch For Window Activate Message

		{
			if (!HIWORD(wParam))					// Check Minimization State

			{
            g_pApp->active=TRUE;						// Program Is Active

			}
			else
			{
				g_pApp->active=FALSE;						// Program Is No Longer Active

			}

			return 0;								// Return To The Message Loop

		}

		case WM_SYSCOMMAND:							// Intercept System Commands

		{
			switch (wParam)							// Check System Calls

			{
				case SC_SCREENSAVE:					// Screensaver Trying To Start?

				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?

				return 0;							// Prevent From Happening

			}
			break;									// Exit

		}

		case WM_CLOSE:								// Did We Receive A Close Message?

		{
			PostQuitMessage(0);						// Send A Quit Message

			return 0;								// Jump Back

		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?

		{
			g_pApp->keys[wParam] = TRUE;					// If So, Mark It As TRUE

			return 0;								// Jump Back

		}

		case WM_KEYUP:								// Has A Key Been Released?

		{
			g_pApp->keys[wParam] = FALSE;					// If So, Mark It As FALSE

			return 0;								// Jump Back

		}

		case WM_SIZE:								// Resize The OpenGL Window

		{
         g_pApp->ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height

			return 0;								// Jump Back

		}
	}

	// Pass All Unhandled Messages To DefWindowProc

	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
  

 - game.cpp -
      
// game.cpp : Defines the entry point for the application.

//


#include "stdafx.h"

int WINAPI WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

   g_pApp->Run();
	return 0;							// Exit The Program

}
      
As you see, all the code has been borrowed from nehe's website, but to learn I always make sure that I rewrite it, and organize it like I like it to be. The first function that is called is Run() and there I had to create this bool fscreen because it didn't like when I changed fullscreen directly for some reason. Now the heat is on CreateGLWindow. Here is what it gives me in debug. First-chance exception in game.exe: 0xC0000005: Access Violation. this points to WindowRect.left=(long)0; It also tells me: CXX0030: Error: expression cannot be evaluated, and when I click on the this tab in debug mode, it tells me that all the expressions that change member data in cApplication cannot be evaluated. I would really like some feedback on what I am doing wrong, and if you need some more info please ask me. The code compiles fine, it is a runtime error. So much for trying to create a window, hehe. Also, I used to have a cApp class derived from cApplication and some few function virtuals to allow some flexibility, but I have deleted it and any reference to it because I really need to make cApplication run first. Thank you for your time, Lois Desplat. [edited by - Lois Desplat on February 18, 2003 3:09:02 PM] [edited by - Lois Desplat on February 18, 2003 3:20:35 PM]
scaught
scaught
Setting g_pApp to something might be useful.
gowron67
gowron67
you aren''t creating the application anywhere.......or initialising the window. or is it that you didn''t post that code for clarity''s sake ?
Lois Desplat
Lois Desplat
Thank you, in the cApplication constructor I added g_pApp = this; which does help but I still get the same problems.
And also if you scroll down you will see that the code to create the window is indeed there.
gowron67
gowron67
what i meant was....in the header file, you have this...

static cApplication *g_pApp = NULL;

as far as I can see, this isn't being created globally anywhere. it's always pointing to NULL. so it doesn't exist. my apologies if I missed it somewhere...

[edited by - gowron67 on February 18, 2003 3:37:50 PM]
Lois Desplat
Lois Desplat
Please hang with me, I do not have strong foundation in C++. I just try to learn through trial and error. I changed the code so that in the cApplication constructor I put: g_pApp = this; Doesn''t this initialize it?
(currently flipping through my C++ reference books).
Thank again for your time.
gowron67
gowron67
yes...you put g_pApp = this in the constructor...but the constructor is never being called. so that statement is never executed and your application doesn''t exist. class constructors only get called if you create them on the stack like this....

cApplication cApp;

or on the heap like this...

cApp = new cApplication.

in both these cases, the class constructor will be called. in your code, the class is never being constructed because you have g_pApp set to NULL in the header file. if you look at nehe''s code, in the winmain function...at the top, he has this code...

COpenGL Game = COpenGL(hInstance);

that is creating a cOpenGL object on the stack ( in this case, it''s scope is just that of the winmain function.

in my humble opinion, there isn''t much advantage to setting up an opengl window in an object orientated way like this...it seems to be object orientated for the sake of it. in all the games I''ve written, the initialisation code for OpenGL is performed using standalone functions. but that''s just my opinion. i''d be happy to help more if you don''t understand
Lois Desplat
Lois Desplat
Thank you,
Indeed you''re right. Now the code is full of bugs, but they''re bugs that I know how to fix. I used to and still am coding on a mud (multiplayer user dungeon) where it is just text and the codebase we use is coded in C. And for some reason, I grew totally distasteful of global functions and such. Thanks a lot for helping me. And doing this really helps me to learn what I am doing wrong and good and what the code means. Just copying and pasting code in doesn''t teach you much while here I actually have to debug and go through the code.
Thanks a lot.
Lois Desplat.

Topic Locked

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

Sign in to reply to this topic.