Jump to content
  • Advertisement
Sign in to follow this  
SticksandStones

OpenGL Problem with glBegin(GL_TRIANGLES)

This topic is 4950 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

I've been trying to learn OpenGL so I was using NeHe's guide to help. So I'm on lesson #2, and I just recently compiled the code to see if everything works so far. Now, using Dev-C++ 4.9.9.1 I get an error from the following code:
    glBegin(GL_TRIANGLES);                               //Drawing using triangles
            glVertex3f(0.0f,1.0f,0.0f);                  //Top
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom left
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottomg right
    glEnd();  
It says that there is a syntax error in glBegin() before the '(' token. Does anybody know what is wrong with this? I have it exzctly as it says in the tuturial and it simply will not accept that line of code ... EDIT: Ugh I'm so stupid, I had an error like 3 lines before it where I forgot the ";" :( EDIT #2: Ok I figured now would be a good time to ask this question as well. I get en error with the:
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
part. A undefined refrence error @32. Here is the total code (some written, some copied and pasted)
/*
 *		This Code Was Created By Jeff Molofee 2000
 *		A HUGE Thanks To Fredric Echols For Cleaning Up
 *		And Optimizing This Code, Making It More Flexible!
 *		If You've Found This Code Useful, Please Let Me Know.
 *		Visit My Site At nehe.gamedev.net
 */

#include <windows.h>		// Header File For Windows
#include <gl\gl.h>			// Header File For The OpenGL32 Library
#include <gl\glu.h>			// Header File For The GLu32 Library
//#include <gl\glaux.h>		// Header File For The Glaux Library

HDC			hDC=NULL;		// Private GDI Device Context
HGLRC		hRC=NULL;		// Permanent Rendering Context
HWND		hWnd=NULL;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application

bool	keys[256];			// Array Used For The Keyboard Routine
bool	active=TRUE;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;	// Fullscreen Flag Set To Fullscreen Mode By Default

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc

GLvoid 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
}
//setup for OpenGL
int InitGL(GLvoid)
{
    glShadeModel(GL_SMOOTH);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClearDepth(1.0f);            //Depth Buffer Setup
    glEnable(GL_DEPTH_TEST);       //Enables Depth Testing
    glDepthFunc(GL_LEQUAL);        //The type of depth test to do
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
   	return TRUE;				  // Initialization Went OK
}

int DrawGLScene(GLvoid)
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);    //Clear the screen and the depth buffer
    glLoadIdentity();                                    //Reset the view
    glTranslatef(-1.5f,0.0f,-6.0f);                      //Move left 1.5 units and into the screen 6.0 units
    glBegin(GL_TRIANGLES);                               //Drawing using triangles
            glVertex3f(0.0f,1.0f,0.0f);                  //Top
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom left
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottomg right
    glEnd();                                             //Finished drawing the triangle
    glTranslatef(3.0f,0.0f,0.0f);                        //Move right 3 units
    glBegin(GL_QUADS);                                   //Draw a Quad
            glVertex3f(-1.0f,1.0f,0.0f);                 //Top Left
            glVertex3f(1.0f,1.0f,0.0f);                  //Top Right
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottom Left
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom Right
    glEnd();                                             //Finished Drawing the triangle
    return TRUE;                                         //Keep going
}

void KillGLWindow(GLvoid)
{
    if (fullscreen)
    {
        ChangeDisplaySettings(NULL,0);
        ShowCursor(TRUE);
    }
    
    if (hRC)
    {
        if (!wglMakeCurrent(NULL,NULL))
        {
                MessageBox(NULL,"Release of DC and RC failes.","SHUTDOWN ERROR",
                MB_OK | MB_ICONINFORMATION);
        }
        
        if (!wglDeleteContext(hRC))
        {
                MessageBox(NULL,"Release of Rendering Context Failed.","Shutdown Error",
                MB_OK | MB_ICONINFORMATION);
        }
        hRC=NULL;
    }
    
    if (hDC && !ReleaseDC(hWnd,hDC))
    {
        MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERR",
        MB_OK | MB_ICONINFORMATION);
        hDC=NULL;
    }
    
    if (hWnd && !DestroyWindow(hWnd))
    {
        MessageBox(NULL,"Could NOt Release hWnd.","SHUTDOWN ERR",
        MB_OK | MB_ICONINFORMATION);
        hWnd=NULL;
    }
    
    if (!UnregisterClass("OpenGL",hInstance))
    {
        MessageBox(NULL,"Couldn't unregister class.","SHUTDOWN ERR",
        MB_OK | MB_ICONINFORMATION);
        hInstance=NULL;
    }
}

//not to create the godblessed window
/*BEGIN BOOL CREATEGLWINDOW()*/
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
    GLuint  PixelFormat;        //holds the results after searing for a match
    WNDCLASS	wc;
    DWORD    dwExstyle;          //Window Extended style
    DWORD    dwstyle;            //window style
    RECT WindowRect;            //Grabs rectangle upper left/lower right values
    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 instnace for our window
    wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;    //Redraw on Move, 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 daya
    wc.hInstance    = hInstance;    //Set the instance
    wc.hIcon    = LoadIcon(NULL, IDI_WINLOGO); //Load the default icon
    wc.hCursor    = LoadCursor(NULL, IDC_ARROW); //Load Arrow Pointer
    wc.hbrBackground    =NULL;    //No background required for GL
    wc.lpszMenuName    =NULL;    //we dont want a menu
    wc.lpszClassName    ="OpenGL";    //Set the Class Name
    
    //The Following code will result in an error message in the even anything goes wrong
    //If it does go wrong, pressing the OK box will close the program
    //+++BEGIN ERROR MESSAGE BOX CODE+++
    if (!RegisterClass(&wc))    //This will tell us if the attempt to register the class failed
    {
        MessageBox(NULL,"Failed to Register the Window CLass.","ERROR",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;
    }
    //+++END ERROR MESSAGE BOX CODE+++
    
    //Checks if the program should run in fullscreen or windowed mode, should go into full screen
    //+++BEGIN FULLSCREEN CHECK+++
    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 Sceen 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 Run in a window.
                if (MessageBox(NULL,"Use Windowed mode instead?","NEHE GL", MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
                {
                        fullscreen=FALSE;                //Selected Window mode (FULLSCREEN=FALSE)
                }
                else
                {
                        //Pop up a messagebox to let user know program is going byebye
                        MessageBox(NULL,"Program is going byebye now.","Sucker...",MB_OK|MB_ICONSTOP);
                        return FALSE;                        //exist and return FALSE, GG noob comp
                }
        }
    }
	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
	}
    //Makes all things the speacified resolution
    AdjustWindowRectEx(&WindowRect, dwstyle, FALSE, dwExstyle);       //Adjust window to true requested size
    if (!(hWnd=CreateWindowEx(    dwExstyle,                 //Extended style for windows
                                  "OpenGL",                  //CLass name
                                  title,                     //Window Title
                                  WS_CLIPSIBLINGS |          //Required Window style
                                  WS_CLIPCHILDREN |          //Required Window style
                                  dwstyle,                   //Selected Window Stlye
                                  0, 0,                      //Window Postion
                                  WindowRect.right-WindowRect.left,                 //Calculage Adjusted Window Width
                                  WindowRect.bottom-WindowRect.top,                 //Calculate Adjusted 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;
    }
    /*++END THE FULLSCREEN CHECK+++*/
    /*04/12/04 16:00*/
    
    /*This section of code describes a Pixel Format. Using a format that supports OPenGL and double buffering
     * We try to find a pixel format that matches the bits we deced on (16,24,32). Finally we set up a 16bit z-buffer.
     *The remaining paramets are eighre not used or not important
     */
    static PIXELFORMATDESCRIPTOR pfd=     //pfd tells the windows how we want stuff to be
    {
        sizeof(PIXELFORMATDESCRIPTOR),    //size of this pixel format dexriptor
        1,                                //Verstion of 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,                   //Requests  an RGBA format
        bits,                           //Select our color depth
        0, 0, 0, 0, 0, 0,                //Color bits ignored
        0,                                //No alpha buffer
        0,                                //shift bits ignored
        0,                                //No accumilation 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 later
        0,                                //Reserved
        0,0,0                             //Layer masks ignroed
    };
    /*If there were no erros while creating the window, we'll attempt to get an OpenGL device context
     *if we cant get a DC an error messae will pop up and program will quit*/
     if(!(hDC=GetDC(hWnd)))     //Did we get a device context?
     {
          KillGLWindow();     //Reset the display'
          MessageBox(NULL,"CANT CREAT A GL DEVICE CONTEXT.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;          //Return false and close the program
     }
     /***IF we managed to get a device context for our OpenGL window we'll try to find a pixel forma that matches the one
      *described above. If Windows can't find a mataching pixel format, an error message will pop up and the program will
      *quit (return false)***/
     if(!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))      //Did windows find a mataching pixel format?
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't find a suitable PixelFormat.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;          //Return False (duh?)
     }
     /***If windows found a pixel format we'll try setting the pixel format, blah blah blah error etc.***/
     if(!SetPixelFormat(hDC,PixelFormat,&pfd))     //Are we able to set the Pixel Format?
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't set the PixelFormat.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     }
     /*If pixel format was set properly we'll try to get a rednering context. If we can't get a rendering context ANOTHER
      *ERROR will pop up and the program will, once again, close*/
     if(!(hRC=wglCreateContext(hDC)))      //Are we able to get a rendering Context?
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Cant create a GL Rendering Context.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     }
     /*IF there are no errors so far, and we've manated to create both a Device Context and a rednering context all we have
      *to do now is make the rendering context active. If we can't make the rendering context active an error message will
      *pop up on the screen and the program will quit*/
     if(!wglMakeCurrent(hDC,hRC))      //Try to active the rendering context
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't activate the GL Rendering Context.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     }
     /*If everything went somoothly, and our OpenGL window was created we'll show the window, set it to be the foreground,
      *and set the focus on that window, then we'll call ReSizeG:SCene passing the screen width and height to set up our
      *perspective OpenGL sceren*/
     ShowWindow(hWnd,SW_SHOW);      //show the window
     SetForegroundWindow(hWnd);     //Slighlt higher priority
     SetFocus(hWnd);               //Sets the keboad focus to the window
     ReSizeGLScene(width, height); //set up our perspective GL Screen
     /*FINALLY, we jump to InitGL() where can set up lighting, texture, and anything else that needs to be setup. */
     if(!InitGL())     //Initialize our newly created GL Window
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Initialization Failed.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;          //Return False
     }
     /*If it has gone this far, it is safe to assume window creation was succesful, we return true to WinMain() preventing it
      *(the program) from crashing*/
     return TRUE;      //Success!
}
/*END BOOL CREATEGLWINDOW()*/
//05/12/04 12:40
/*The next part is where all the window messages are dealth with. When we registeeed the window class we told it to come here 
 *to deal with window message */
/*+++BEGIN CASES+++*/
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 winows messages
     {
            case WM_ACTIVATE: //watch for window activate message
            {
                 if(!HIWORD(wParam))  //Check for Minimization state
                 {
                      active=TRUE;  //Program is active
                 }
                 else
                 {
                     active=FALSE;  //Program is no longer active
                 }
                 
                 return 0;
            }
            case WM_SYSCOMMAND:     //intercept System COmmands
            {
                 switch (wParam)    //Check system calls
                 {
                        case SC_SCREENSAVE: //Screensaver is trying to start
                        case SC_MONITORPOWER:             //Monitor trying to enter powersave?
                        return 0;                         //prevent from happenning
                 }
                 break;
            }
            case WM_CLOSE:     //Did we receive a cloase message?
            {
                 PostQuitMessage(0); //Send a quit message
                 return 0;           //Jump back
            }
            case WM_KEYDOWN:         //Is a key being held down?
            {
                 keys[wParam]=TRUE;  //if so mark it as TRUE
                 return 0;           //Jump back
            }
            case WM_SIZE:            //Resize the OpenGL Window
            {
                 ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); //LoWord=width, Hiord=Height
                 return 0;                                     //jump back
            }
     }
     //pass all unhandled mesages to DefWindowProc
     return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
/*+++END CASES+++*/

/*This is the entry point of our Windows Application. This is where we call our window creation routine, deal with window
 messages, and watch for human interaction.*/
/*+++BEGIN WINAPI WINMAIN()+++*/ 
int WINAPI WinMain(  HINSTANCE     hInstance,     //Instance
                     HINSTANCE     hPrevInstance, //Previous Instance
                     LPSTR         lpCmdLine,     //Command Line Parameters
                     int           nCmdShow)      //Window Show State
{
     MSG msg;        //Windows Message Structure
     BOOL done=FALSE;//Bool variablo to exit loop
     //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)
     {
          fullscreen=FALSE;    //Windowed Mode
     }
     //Create our openGL window
     if(!CreateGLWindow("NeHe's OpenGL Freamework",640,480,16,fullscreen))
     {
          return 0;             //Windowed Mode
     }
     while(!done)               //Loop that runs until done=TRUE
     {
          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 form DrawGLScene()
                   if (active)       //Program active?
                   {
                        if(keys[VK_ESCAPE])    //Was ESC pressed?
                        {
                             done=TRUE;        //ESC signalled a quit
                        }
                             else              //Not time to quit, update screne
                             {
                                  DrawGLScene();     //Draw The Scene 
                                  SwapBuffers(hDC);  //Swap Buffers
                             }
                        }
                        //now to allow for switching between fullscreen and windoed
			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
				}
			}
		}
	}
          
         //if Done=TRUE program should quit
          //shutdown
          KillGLWindow();        //Kill the window
          return(msg.wParam);   //Exit the program
}

Share this post


Link to post
Share on other sites
Advertisement
Show us the whole function, not just the line where it says the error is. Also, are you remembering to include gl.h?

Share this post


Link to post
Share on other sites
The linker error most likely means you've forgotten to link glu32.lib when building the program.

Share this post


Link to post
Share on other sites
Quote:
Original post by Flax
The linker error most likely means you've forgotten to link glu32.lib when building the program.
Thank you! I got it to compile, thank you so much!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!