0% found this document useful (0 votes)
134 views50 pages

2014 OpenGLGlut

This document provides an overview of OpenGL and GLUT (OpenGL Utility Toolkit) for computer graphics programming. It lists several popular OpenGL reference books and tools for checking OpenGL extensions and versions. GLUT is introduced as a portable windowing API that provides basic window operations to simplify OpenGL application development. Key aspects of setting up OpenGL and GLUT projects in Visual C++ are also covered, such as linking libraries and header files. Typical OpenGL/GLUT program structure and functions for initialization, callbacks, and the main event loop are demonstrated. Finally, different types of events in GLUT like display, reshape, and user input events are described.

Uploaded by

Wa Chio Leong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views50 pages

2014 OpenGLGlut

This document provides an overview of OpenGL and GLUT (OpenGL Utility Toolkit) for computer graphics programming. It lists several popular OpenGL reference books and tools for checking OpenGL extensions and versions. GLUT is introduced as a portable windowing API that provides basic window operations to simplify OpenGL application development. Key aspects of setting up OpenGL and GLUT projects in Visual C++ are also covered, such as linking libraries and header files. Typical OpenGL/GLUT program structure and functions for initialization, callbacks, and the main event loop are demonstrated. Finally, different types of events in GLUT like display, reshape, and user input events are described.

Uploaded by

Wa Chio Leong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

CISB355

Computer Graphics
OpenGL and GLUT Programming

Dr. WU Wen, FST, UM

OpenGL:Beginning
Beginning
OpenGL:
OpenGL reference books:
1. The RED BOOK: Mason Woo, Neider, Jackie, Tom Davis,
Dave Shreiner, OpenGL Programming Guide, 8th Edition, The
Official Guide to Learning OpenGL, Version 4.3 2013.
2. The BLUE BOOK: OpenGL ARB, OpenGL Reference Manual,
4th Edition, The Official Reference Document to OpenGL,
Version 1.4, 2004.
3. Richard S. Wright, et. al. OpenGL SuperBible, 6th Edition, 2014.
Companion website: http://www.starstonesoftware.com/OpenGL/
(OpenGL 4.3)
4. Randi J, Rost, et. al. OpenGL Shading Language, 3rd Edition by AddisonWesley Professional, 2009. (OpenGL 3.1)

Tool: GLview
OpenGL Extensions Viewer: to check which version your
hardware supports
The vendor name
The OpenGL version
The renderer name
The extensions of the current OpenGL 3D accelerator
http://www.realtech-vr.com/glview/version4.html
Now supporting OpenGL 3.0 to 4.1 with rendering tests.
GLView

OpenGL and GLUT (OpenGL Utility Toolkit)


OpenGL is not a programming language, but graphics rendering API
(application programming interface).
With OpenGL, you can write your own programs which can do modeling
and projection transformation, display 3D objects with lighting effects,
shading, and custom texture maps, realize the rendering effect of antialiasing, animation, fog, motion blur, etc.
GLUT is a portable windowing API for OpenGL, but not officially part of
OpenGL. It is written by Mark Kilgard and is a window system independent
toolkit in public domain for making simple OpenGL applications.
It provides a number of the basic window operations, including:
Initialize OpenGL state
Register input callback functions: keyboard, mouse, etc.
Render
Resize
Enter event processing loop
4

OpenGL API for graphics programming


Related libraries, dlls and include files
Basic Lib
opengl32.lib
in
gl()
-- 224 core functions (OpenGL4.1)
Utility Lib
glu32.lib
in
glu()
-- 43 functions, for describing viewing and projection,
complex objects, quadrics and B-Splines, surface
rendering
Auxiliary Lib
glaux.lib in
aux()
-- 31 functions, for Windows OS mainly
Utility Toolkit Lib glut32.lib
in
glut()
-- about 30 functions, for interacting with any screenwindow system, plus quadric curves and surfaces.
Dynamic Link Lib: opengl32.dll
glu32.dll
glut32.dll

Header Files: gl.h


glu.h
glut.h
glaux.h
(windows.h)
5

How to setup?
Setup OpenGL&GLUT in VC6.0
Setup OpenGL&GLUT in VS2008
Setup OpenGL&GLUT in VS2010 Express

GLUT settings key points


Download the GLUT files from the web.
glut32.lib, glut.h, glut32.dll
Copy glut32.dll into the windows directory
C:\WINDOWS\system32\
Copy glut.h to <drive>: \<VC++ path>\include\GL\glut.h

or to <drive>: \Program Files>\Microsoft SDKs\ Windows\


v6.0A\Include\GL\glut.h
(VC2008)
to <drive>: \Program Files>\Microsoft SDKs\ Windows\
v7.0A\Include\GL\glut.h
(VC2010)

Copy glut32.lib to <drive>: \<VC++ path>\lib\glut32.lib


or to <drive>: \Program Files>\Microsoft SDKs\ Windows\

v6.0A\Lib\GL\glut32.lib
(VC2008)
to <drive>: \Program Files>\Microsoft SDKs\ Windows\
v7.0A\Lib\GL\glut32.lib
(VC2010)
7

Compilation on Windows
Visual C++
Create a Win32 console application
Add path to find include files if needed (GL/glut.h)
Add opengl32.lib, glu32.lib, glut32.lib to project
settings (for library linking VC6)
glut32.dll is used during the program execution.
(Other DLL files are included in the device driver
of the graphics accelerator.)

Simplest OpenGL program


# include <GL/glut.h>
void myInit()
{
glClearColor(0.0f, 0.0f, 1.0f, 0.0f);
}

//OpenGL initialization

void display()

//called to draw scene

//use blue to clear the color buffer

{
glClear(GL_COLOR_BUFFER_BIT);

//clear the window with current clearing color

glFlush();

//flush drawing commands

}
void main ()
{
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutCreateWindow(Simple OpenGL );
myInit();
glutDisplayFunc(display);
glutMainLoop();
}

void main (int argc, char ** argv)


Example in Chapter 3
{
//Initialize GLUT
glutInit(&argc, argv);
//Set display mode
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
//set top-left display-window position
glutInitWindowPosition(50, 100);
//set display window width and height
glutInitWindowSize(400, 300);
define window
//create display window
properties
glutCreateWindow(Line Segment);
myInit();

set some OpenGL states

//Send graphics to display window


glutDisplayFunc(display);

display callback

//Display everything and wait


glutMainLoop();
}

enter event loop

10

Typical OpenGL/GLUT Main Program


void main (int argc, char ** argv)
{
glutInit(&argc, argv); //Initialization
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); // set display mode
glutInitWindowPosition(50, 100); // initial display-window position
glutInitWindowSize(400, 300);
// initial display-window size
glutCreateWindow(Display Window Title); // create display-window
myInit();

// your own initializations

initialize callbacks here (described later)


glutMainLoop(); // turn control over to glut
}

11

Program structure
Most OpenGL programs have a similar structure
that consists of the following functions
main():
opens one or more windows with the required properties
defines the callback functions
enters event loop (last executable statement)

init(): sets the state variables


viewing
Attributes

callbacks
display function
input and window functions

12

Inside the main()


Initialization
glutInit(&argc, argv);
It must be called before any non-glutInit-prefix
GLUT or OpenGL routines.
It does general initialization of GLUT and OpenGL.
glutInit(&argc, argv): the parameters to glutInit()
should be the same as those to main(), that is
main(int argc, char** argv).
These command-line arguments may be of interest
to GLUT and the window system.
13

Inside the main()


glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);

It specifies the display mode for a window (OpenGL:


how to setup the frame buffer).
The argument is a bitwise OR-ing of a number of
possible options, which are given in the following
as example:
GLUT_RGB, GLUT_RGBA, GLUT_INDEX,
GLUT_DOUBLE, GLUT_SINGLE, GLUT_DEPTH,
GLUT_ACCUM; GLUT_STEREO;

14

More detail

Color: to tell the system how colors will be


represented.
Single or Double Buffering
In double buffering, the system maintains two separate
frame buffers.
front buffer is the one that is displayed;
back buffer is the one that is written to. Drawing is always
done to the back buffer.
To update the image, the system simply swaps the two

buffers.
15

More detail (cont.)


Program requests a double buffer
glutInitDisplayMode(GL_RGB|GL_DOUBLE)
At the end of the display callback buffers are
swapped
void mydisplay()
{
glClear()
.
/* draw graphics here */
.
glutSwapBuffers()

16

More detail (cont.)

Depth Buffer: stores the distance (or depth) of


each pixel from the viewer.
It is used in the hidden surface removal of the 3D
applications.
A fastest and easiest (but most space-consuming)
way.

17

glutInitWindowSize(400, 300);

General form is glutInitWindowSize (int width, int height)


Used to specify the size, in pixels, of your initial window.


glutInitWindowPosition(50, 100);

glutInitWindowPosition(int x, int y), where the (x, y) coordinates


are given relative to the upper left corner of the display.
Specify the screen location of the upper-left corner of your initial
window.

Creating a Window
 glutCreateWindow(xxxx);
glutCreateWindow() create the graphics window. It takes a
character string as a parameter which may appear in the title
bar.
Note: It only sends a request of the windows creation to the system.
The window is not really to be displayed until glutMainLoop is
18
entered.

Event-driven programming and callbacks


Event Driven: for all interactive graphics programs.
Input can come at any time from any number of sources:
the mouse, keyboard, or other graphics devises such as
trackballs and joysticks
Programs should prepare at any time for these input

In GLUT this is done through the use of callbacks.


The graphics program instructs the system to invoke a
particular procedure whenever an event of interest occurs
Tell the window system which type of event need to be processed;
How to process it: user-defined functions.

19

Event processing
GLUT is designed as an event-driven engine
Each one of the possible events must be registered
in one of the GLUT state variables, by callback
registration routines, such as glutMouseFunc;
glutDisplayFunc;
Callback Registration Routine Syntax
g l u t [SomeEvent] F u n c
e.g.: mouse clicking - glutMouseFunc
a routine written by user - myMouse()
To register the callback function by
glutMouseFunc( myMouse );
20

Event processing (cont.)


GLUT is designed as an event-driven engine
A continuous loop (the event processing loop), that
gets started after the proper initializations,
processes all the events one by one.
If the event occurs, the callback function will be
called to process it.
For example: myMouse()

21

Event processing routine


glutMainLoop()
It will let the program enter an infinite event loop;

In each pass of the loop, GLUT


- looks at the events in the queue;
- if the event is defined, GLUT executes the appropriate
callback function;
- if no callback is defined for the event, the event is ignored.
Note: Every main() for an OpenGL application must end in a
glutMainLoop() statement.

22

Types of event
System events
Display event
Reshape event
Idle event and timer event
User input events
Mouse click, motion of the mouse, keyboard hits

23

Types of event (cont.)


System events
Display event: every OpenGL program must
handle.
Invoked when GLUT senses the window should
be refreshed.
Which cases can invoke it ?
The window is first displayed
The window is reshaped
An occluded window is exposed
The program explicitly requests redrawing

24

Types of event (cont.)


System events (cont.)
Reshape event: happens whenever the windows
size is altered.
The callback provides information on the new size of the
window.

Idle event and timer event


Idle event
generated every time the system has nothing better
to do - generate a huge number of events
Timer event
you request that your program go to sleep for some
period of time and that it be awakened by an event
some time later, say 1/30 of a second later.
25

Event and callback


The idle callback for animations
glutIdleFunc(myidle)
void myidle()
{
/* change something */
t += dt
glutPostRedisplay();
}
void mydisplay()
{
glClear();
/* draw something that depends on t */

glutSwapBuffers();
}
26

Event and callback (cont.)


The timer callback for animations

glutTimerFunc()
Three arguments:
the sleep time as an integer in milliseconds
the users callback function
an integer identifier, which is passed into the
callback function
If multiple timer callbacks requested

27

Event and callback (cont.)


The timer callback for animations (cont.)
Note: each call to glutTimerFunc() creates only one
request for a timer event. It is not automatically
repeated.
If you want to generate the timer event on a regular
basis, then insert a call to glutTimerFunc() within
the callback function to generate the next one.

28

Events and their callback function


prototypes

Example: display events, reshape events, mouse


clicks, keyboard strikes, and timer events

29

What does a typical callback function do?


Depend entirely on the application that you are
designing
Examples of general form of callback functions:

30

Parameters of callback functions


Each callback function is provided with information
associated with the event.
A reshape event callback: pass in the new
window width and height
A mouse click callback: pass in four arguments

which button was hit (b: left, middle, right)


what the buttons new state is (s: up or down)
the (x, y) coordinates of the mouse when it was clicked
(in pixels)
31

Parameters of callback functions (cont.)

The various parameters used for b and s

32

Parameters of callback functions (cont.)


A keyboard event callback
Parameters: the key that was hit and the current
coordinates of the mouse

A timer event callback:


Parameter: the integer identifier of the timer
event which caused the callback

33

GLUT menu functions


To add simple pop-up menus and submenus
glutCreatMenu (menuFcn);
void menuFcn (GLint menuItemNumber);
glutAddMenuEntry (charString, menuItemNumber);
Text in menu

Location in the menu

Then to specify a mouse button to be used to


select a menu option
glutAttachMenu (button);
34

GLUT menu functions


A menu of two displaying options of the interior fill
of triangle

code

35

Using global
The form of all GLUT callbacks is fixed
void mymouse(GLint button, GLint state,
GLint x, GLint y)
void mydisplay()
It must use globals to pass information to callbacks
float t; /*global */
void mydisplay()
{
/* draw something that depends on t */
}

36

Drawing and viewports


To draw a scene in the window, OpenGL needs to
know
What are the objects to be drawn
How is the image to be projected onto the
window
How lighting and shading are to be performed
A very simple case: 2D objects, no lighting and
shading

37

Display callback
The most important callback
 glutDisplayFunc(xxxx);
Put all your routines that you need to draw a scene in
the display callback function.
Display callback It is called whenever it is necessary to
redraw the image, such as:
The initial creation of the window;
Whenever the window is uncovered by the removal of some
overlapping window;
Whenever the program explicitly requests the redrawing
(through the use of glutPostRedisplay() function, as in the case
of an animation, where this would happen continuously).38

Display callback (cont.)

Clearing the window


The background color is set by glClearColor(GLfloat Red,
GLfloat Green, GLfloat Blue, GLfloat Alpha)
glClear() clears the window by applying the background color to
the color buffers in RGBA mode.
39

Drawing commands
glBegin(mode)

glEnd()
Between these two commands a list of vertices is
given, which defines the object.
The sort of object to be defined is determined by
the mode argument.

40

Drawing commands (cont.)


Some OpenGL object definition modes

41

OpenGL Command Syntax

1. glVertex2i(2, 4)
2. glVertex3ub(3, 4, 5)

3. glVertex3iv(const GLint *v)


static GLint v[3]={3, 4, 5};

42

Drawing
commands
All valid Commands
between glBegin()
and glEnd()
(refer to Red book)
NO others!

43

Drawing commands (cont.)


Other drawing attributes other than color
Point size
Line width
Line style
Fill pattern
Characters

Other settings such as:


glPointSize(GLfloat size);
glLineWidth(GLfloat width);
glLineStipple(GLint factor, GLushort pattern);
44

Back to example: viewport

Viewport: the subwindow into which the current


graphics are being drawn
The viewport is typically the entire display window, but it
may generally be any rectangular subregion for drawing.
The size depends on the dimensions of the window.
Every time the window is resized we need to readjust the
viewport to ensure proper transformation of the graphics.

45

Reshape callback
The reshape callback would contain the following
call which resizes the viewport, whenever the
window is resized.

glViewport(GLint x, GLint y, GLsizei width, GLsizei height)


where (x, y) are the pixel coordinates of the lower-left corner
of the viewport, as defined relative to the lower-left corner of
the window, and width and height are the width and height of
the viewport in pixels.

46

Projection
Map the drawing region to the window
In this simple example: the drawing area is a unit
square over the interval [0, 1] with the origin in
the lower left corner
Firstly, inform OpenGL where the idealized
drawing area is. Then OpenGL can map it to the
viewport by a transformation matrix: projection
matrix.
gluOrtho2D(left, right, bottom, top)
Any drawing outside of this region will automatically be
clipped away by OpenGL.

47

2D projection
The first command tells OpenGL to modify the projection
transformation.
Then, initialize the current matrix to the identity

Dont confuse the viewport and projection


Viewport: a rectangle within the actual window on your
display, where to show you graphics.
gluOrtho2D(): a range to define what you want to show of
your objects.

48

The sample
program

49

End of the introduction of


OpenGL&GLUT programming

You might also like