Help end child hunger

Initialization

Prev: Setup Basics Next: Reshape
 

In this section we’re going to build the main function of our application. The main function will perform the required initializations and start the event processing loop.

The first part of our main function code will initialize GLUT and create the window.

After GLUT enters the event processing loop it gains control of the application. GLUT will wait for an event to occur and then will check if there is a function to process it.

So before GLUT enters its event processing loop we need to tell which functions GLUT must call for each event we care to process.

At this point you might wonder what is an event. An event is something like a key pressed, a mouse move, a window that needs to be painted, or a window that was resized, or … The list can grow to become quite large. We will start by only dealing with the paint event.

Telling GLUT which function to call back when an event occurs is registering the callback function. For each event type GLUT provides a specific function to register the callback function.

The skeleton of our main function is going to start as:

int main(int argc, char **argv) {

	// init GLUT and create window

	// register callbacks

	// enter GLUT event processing cycle

}

Init GLUT and create window

All the functions in GLUT have the prefix glut, and those which perform some kind of initialization have the prefix glutInit. The first thing you must do is call the function glutInit.


void glutInit(int *argc, char **argv);

Parameters:

  • argc – A pointer to the unmodified argc variable from the main function.
  • argv – A pointer to the unmodified argv variable from the main function.

 


 

After initializing GLUT itself, we’re going to define our window. First we establish the window’s position, i.e. its top left corner. In order to do this we use the function glutInitWindowPosition.


void glutInitWindowPosition(int x, int y);

Parameters:

  • x – the number of pixels from the left of the screen.
    -1 is the default value, meaning it is up to the
    window manager to decide where the window will appear.
    If not using the default values then you should pick
    a positive value, preferably one that will fit in your screen.
  • y – the number of pixels from the top of the screen.
    The comments mentioned for the x parameter
    also apply in here.

Note that these parameters are only a suggestion to the window manager. The window returned may be in a different position, although if you choose them wisely you’ll usually get what you want.

Next we’ll choose the window size. In order to do this we use the function glutInitWindowSize.


void glutInitWindowSize(int width, int height);

Parameters:

  • width – The width of the window
  • height – the height of the window

Again the values for width and height are only a suggestion, so avoid choosing negative values.

Then you should define the display mode using the function glutInitDisplayMode.


void glutInitDisplayMode(unsigned int mode)

Parameters:

  • mode – specifies the display mode

The mode parameter is a Boolean combination (OR bit wise) of the possible predefined values in the GLUT library. You use mode to specify the color mode, and the number and type of buffers.

The predefined constants to specify the color model are:

  • GLUT_RGBA or GLUT_RGB – selects a RGBA window. This is the default color mode.
  • GLUT_INDEX – selects a color index mode.

The display mode also allows you to select either a single or double buffer window. The predefined constants for this are:

  • GLUT_SINGLE – single buffer window
  • GLUT_DOUBLE – double buffer window, required to have smooth animation.

There is more, you can specify if you want a window with a particular set of buffers. The most common are:

  • GLUT_ACCUM – The accumulation buffer
  • GLUT_STENCIL – The stencil buffer
  • GLUT_DEPTH – The depth buffer

So, suppose you want a RGB window, with double buffering, and a depth buffer. All you have to do is to OR all the respective constants in order to create the required display mode.

glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT DEPTH);

After all the above steps, the window can be created with glutCreateWindow.


int glutCreateWindow(char *title);

Parameters:

  • title – sets the window title

The return value of glutCreateWindow is the window identifier. You can use this identifier later within GLUT but this is outside of the scope of this section.

So now here is a little bit of code to perform all the initializations:

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

int main(int argc, char **argv) {

	// init GLUT and create Window
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
	glutInitWindowPosition(100,100);
	glutInitWindowSize(320,320);
	glutCreateWindow("Lighthouse3D- GLUT Tutorial");

	return 1;

}

Note the include statements at the beginning of the code. The required include file comes with the GLUT distribution, however their location is different on MacOS systems, hence checking is required if the code is to be cross-platform.

The render function and callback registration

If you run this code, you’ll obtain an empty black console window but no OpenGL window. There are two things left to do before we are ready to render something. The first is to tell GLUT what is the function responsible for the rendering. This function will be called by GLUT everytime the window needs to be painted.

Lets create an example function for the rendering. The function presented bellow will clear the color buffer and draw a triangle.

void renderScene(void) {

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glBegin(GL_TRIANGLES);
		glVertex3f(-0.5,-0.5,0.0);
		glVertex3f(0.5,0.0,0.0);
		glVertex3f(0.0,0.5,0.0);
	glEnd();

	glutSwapBuffers();
}

The name of this function is up to you. However, now you must tell GLUT that it should use the function we just wrote for the rendering. This is called registering a callback. GLUT will call the function you choose whenever rendering is required.

So lets tell GLUT that the function renderScene should be used whenever the window requires to be painted. GLUT has a function that takes as a parameter the name of the function to use when redrawing is needed. Note: the function you supply as a parameter is also called the first time the window is created. The syntax is as follows:


void glutDisplayFunc(void (*funcName)(void));

Parameters:


GLUT event processing loop

One last thing is missing, telling GLUT that we’re ready to get in the event processing loop. GLUT provides a function that gets the application in a never ending loop, always waiting for the next event to process. The GLUT function is glutMainLoop, and the syntax is as follows:

void glutMainLoop(void)

All together now

The code so far is presented bellow. If you try to run this code you’ll get a console window, and a few instants after the OpenGL window with a white triangle, hopefully at the desired position and with the desired size.

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

void renderScene(void) {

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glBegin(GL_TRIANGLES);
		glVertex3f(-0.5,-0.5,0.0);
		glVertex3f(0.5,0.0,0.0);
		glVertex3f(0.0,0.5,0.0);
	glEnd();

        glutSwapBuffers();
}

int main(int argc, char **argv) {

	// init GLUT and create Window
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
	glutInitWindowPosition(100,100);
	glutInitWindowSize(320,320);
	glutCreateWindow("Lighthouse3D - GLUT Tutorial");

	// register callbacks
	glutDisplayFunc(renderScene);

	// enter GLUT event processing cycle
	glutMainLoop();
	
	return 1;
}

 

Prev: Setup Basics Next: Reshape
 

51 Responses to “Initialization”

  1. When I debug any kind of C++ project in Visual Studio 2010 it says it needs dxerr.lib.
    The only reason I can put towards it doing this is because in Linker, Additional Dependencies, Inherited Values, dxerr.lib and a few other Direct X libraries are there and I don’t seem able to remove them, can you maybe shred some light on this? I’ve had a miserable day of going through 4 different kinds of Glut getting this to work.
    Awesome website by the way, everything is very well documented. :)

  2. Hey, I’m having a problem, my code is exactly as yours but, while I see a new app pop up in Dock(using Mac), nothing is drawn on the screen. It’s responding and all, the console is working and not displaying any errors, but there’s just nothing being drawn.

    I’m using XCode by the way.

  3. Fantastic job. Everything works as explained, and I am helpless when instructions are not exactly right.

  4. Your code for the triangle is wrong, it’s supposed to be:

    glVertex3f(-0.3,0.0,0.0);
    glVertex3f(0.3,0.0,0.0);
    glVertex3f(0.0,0.5,0.0);

  5. The tutorial is great…well done!
    I am having a problem that is…
    I have created a function consisting of all the statements that are presented in the “main()” function then i have created DLL of this sample code and calls it in Windows application so that the drawing must be on my Form not on Glut window…
    The control exit its execution when it reaches the CreateWindow() statement.
    can you tell me the answer if possible?

  6. I’ve got a pretty strange error message. After dithering for awhile, I copy/pasted the code, and got the following error message(s) from xcode:

    Undefined symbols:
    “_glutInitDisplayMode”, referenced from:
    _main in main.o
    “_glutInit”, referenced from:
    _main in main.o
    “_glutInitWindowPosition”, referenced from:
    _main in main.o
    “_glutCreateWindow”, referenced from:
    _main in main.o
    “_glutInitWindowSize”, referenced from:
    _main in main.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status

    A little confusing, to be sure. I have no idea where or what main.o is.

    • Hi Kcaj,

      I’m not familiar with xcode, but it seems that you did not include the glut framework.

      • No, it’s definitely including GLUT. There are no build errors besides what I copied and pasted; if there were an error with inclusion, g++ would have said so.

      • Never mind, solved it. It turns out that yes, I had forgotten to include the framework, but the message was so cryptic that I thought otherwise. Kind of embarrassing.

  7. last try :)
    #include windows.h

  8. Actually, there’s a better way to get rid of that error due to stdlib:
    #include first in the file
    Also, to center the window to your desktop:
    #define WINDOW_WIDTH 640
    #define WINDOW_HEIGHT 480
    void GetDesktopResolution(int& width, int& height)
    {
    RECT desktop;
    HWND hDesktop = GetDesktopWindow();
    GetWindowRect(hDesktop, &desktop);
    width = desktop.right;
    height = desktop.bottom;
    }

    then the init sequence:

    glutInitWindowPosition((screenWidth – WINDOW_WIDTH)/2, (screenHeight – WINDOW_HEIGHT)/2);
    glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);

    Cheers!

  9. Please explain how glVertex3f is work.. you use it for draw but how it’s work??? (x,y,z)? who mean first is x axis, the second is y axis and last is z axis? If is that please help me how to use it.

    • yes, x refers to the x axis. the horizontal line.
      y refers to the y axis, the vertical line.
      z however, refers to the depth. z-axis. It is the line pointing at you. (x, y, z) is the plane used for 3D rendering.

  10. i got BSOD i dont know why..

  11. Firstly, a great tutorial! However, I notice that you end some of your code samples with return 1;. Shouldn’t, it return an exit code of 0, signifying a successful execution?

  12. only console window appears every time I run this program my code with some modification is: #include int main(int argc, char **argv) { // init GLUT and create Window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100,100); glutInitWindowSize(320,320); glutCreateWindow(“Lighthouse3D- GLUT Tutorial”); // register callbacks glutDisplayFunc(renderScene); // enter GLUT event processing cycle glutMainLoop(); return 1; } void renderScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBegin(GL_TRIANGLES); glVertex3f(-0.5,-0.5,0.0); glVertex3f(0.5,0.0,0.0); glVertex3f(0.0,0.5,0.0); glEnd(); glutSwapBuffers(); } i had to ommit those headers to eliminate errors but it still isnt running :’(

  13. This seems to be a really good tutorial, except that, despite it being programmed in a .cpp, it’s all C, and I can’t get the callback function registering to work with a C++ class structure. Why is it every tutorial I see for this that claims to be C++ only uses C coding?

  14. Hello, wonderful tutorial. When compiling I got some errors, maybe someone could help me figure out what is wrong? Undefined symbols for architecture x86_64: "_glClear", referenced from: renderScene() in cctLZbOx.o "_glBegin", referenced from: renderScene() in cctLZbOx.o "_glVertex3f", referenced from: renderScene() in cctLZbOx.o "_glEnd", referenced from: renderScene() in cctLZbOx.o "_glutSwapBuffers", referenced from: renderScene() in cctLZbOx.o "_glutInit", referenced from: _main in cctLZbOx.o "_glutInitDisplayMode", referenced from: _main in cctLZbOx.o "_glutInitWindowPosition", referenced from: _main in cctLZbOx.o "_glutInitWindowSize", referenced from: _main in cctLZbOx.o "_glutCreateWindow", referenced from: _main in cctLZbOx.o "_glutDisplayFunc", referenced from: _main in cctLZbOx.o "_glutMainLoop", referenced from: _main in cctLZbOx.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status [Finished in 0.1s with exit code 1] I’m using OS X Lion.

  15. thanks for the tutorial, it’s awesome!

  16. hello there,how can I do the entire things in opengl ES??please help me …your materials are so helpful……

  17. very nice tutorial ..loving it..
    i have a simple question. How do we change the color of that triangle to other color of our choice?

    • Thanks.

      Use glColor3f( ___ , ____ , ___); and just fill in the blanks with RGB values between 0 and 1.

  18. Hey

    This is using opengl 2 right? I’m trying to find opengl 3.3 + glut tutorials, but seems there’s nothing to find anywhere…

    • Yes, the GLUT tutorial is OpenGL 2.0. There are code samples which are OpenGL 3.3 in the “CG Topics” section.

  19. Nice tutorial, saves a lot of time to use glut

  20. Hey, how do i prevent the console window from disappearing? it compiles, no errors, but the window disappears before i can see what is rendered? Your help is appreciated. Thanks a lot!

  21. Hi,
    Thank you for the tutorial. Can you explain the purpose of glutSwapBuffers() and more about the Display Modes used in calling the glutInitDisplayMode() function.

    • Most graphic systems work with double or triple buffering. What this means is that there is a buffer being presented on the screen, while another is being drawn. At the end of the frame the buffers are swapped. That’s why you set GLUT_DOUBLE on the display settings. Another setting relates to the type of output, more specifically we usually want an RGBA output, i.e. RGB plus alpha. The final setting relates to the Z-buffer, aka depth buffer, which stores the depths of the pixels currently on the screen, and prevents a pixel from being written if its further away than the pixel in the frame buffer.

  22. How to set up to have the OpenGL window open when I hit “Run” ( i have set the auto build). Now I will have to go to the Windows Explorer to click on the .exe file.

    Thanks.

  23. hai~ i hve errors at openGl source..
    what should i do? thank you :)
    error :

    ——————–Configuration: Tugas UAS Grafika Komputer – Win32 Debug——————–
    Linking…
    main.obj : error LNK2001: unresolved external symbol __imp__glEnable@4
    main.obj : error LNK2001: unresolved external symbol _gluPerspective@32
    main.obj : error LNK2001: unresolved external symbol __imp__glLoadIdentity@0
    main.obj : error LNK2001: unresolved external symbol __imp__glMatrixMode@4
    main.obj : error LNK2001: unresolved external symbol __imp__glViewport@16
    main.obj : error LNK2001: unresolved external symbol __imp__glClearAccum@16
    main.obj : error LNK2001: unresolved external symbol __imp__glClearColor@16
    main.obj : error LNK2001: unresolved external symbol __imp__glShadeModel@4
    main.obj : error LNK2001: unresolved external symbol _glutSolidIcosahedron@0
    main.obj : error LNK2001: unresolved external symbol _glutWireDodecahedron@0
    main.obj : error LNK2001: unresolved external symbol _glutWireOctahedron@0
    main.obj : error LNK2001: unresolved external symbol __imp__glPopMatrix@0
    main.obj : error LNK2001: unresolved external symbol _glutSolidTetrahedron@0
    main.obj : error LNK2001: unresolved external symbol __imp__glTranslatef@12
    main.obj : error LNK2001: unresolved external symbol __imp__glPushMatrix@0
    main.obj : error LNK2001: unresolved external symbol __imp__glClear@4
    main.obj : error LNK2001: unresolved external symbol __imp__wglMakeCurrent@8
    main.obj : error LNK2001: unresolved external symbol __imp__wglCreateContext@4
    main.obj : error LNK2001: unresolved external symbol __imp__wglDeleteContext@4
    LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
    Debug/Tugas UAS Grafika Komputer.exe : fatal error LNK1120: 20 unresolved externals
    Error executing link.exe.

    Tugas UAS Grafika Komputer.exe – 21 error(s), 0 warning(s)

  24. Wow! So far (I only started studying this tut. now), this tut. seems very explanatory and easy to understand. Thanks!

    A friendly suggestion though: I think it would be better if pieces of code (aside from the code samples in gray boxes i.e. “void glutInit(int *argc, char **argv);”) should be high-lighted, maybe by making them bold. The same goes with words being defined in the definitions (the ones preceded by a bullet i.e. “width” and “height”).

    Also, I’m somewhat confused as to the purpose of void glutInit(int *argc, char **argv); function. It’s because I seem to be able to run GLUT/OpenGL programs without it. So I’d really appreciate if you would elaborate it for me. Thanks! :-)

    • Hi Mick,

      Thanks for the suggestions. As for your question, and according to the spec: “glutInit will initialize the GLUT library and negotiate a session with the window system.” So in theory it should be essential. glutInit also parses command line options, however note that these vary from window system to window system. I’ve never used the command line options so I can’t tell you which ones are really implemented. I suggested reading the man page.

  25. awesome man, thanks!

  26. The code says glSwapBuffers(); which should be glutSwapBuffers();

  27. Hi there,

    Thanks very much for this tutorial. FYI though, I found that I had to include a glutSwapBuffers() call in the renderScene function to get this code to work with the GLUT_DOUBLE setting.

    Cheers,

    Blake

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2014 Lighthouse3d.com Suffusion theme by Sayontan Sinha