517543243-Appendix

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Appendix: OpenGL -

APPENDIX: OPENGL-A QUICK START A Quick Start

Structure Page No
1.1 Introduction 111
Objectives
1.2 A Brief Overview 112
1.3 How to Install OpenGL? 114
1.4 Your First Program Using OpenGL 115
1.5 OpenGL Functions, Constants and Data Types 119
1.6 OpenGL Transformation Functions 122
1.7 Animation 123
1.8 Mouse and Keyboard Functions 125

1.1 INTRODUCTION
OpenGL stands for Open Graphics Library. By using it, you can create
interactive applications that render high-quality color images composed of 3D
geometric objects and images. Here the term 'Open' indicates open standards,
which means that many companies are able to contribute to the development of
OpenGL.

OpenGL is a powerful low-level graphics rendering and imaging library


available on all major platforms. It provides the programmers an interface to
the systems graphics hardware. OpenGL is designed to be a device which is
window and operating system independent and allows portability between
various computer platforms (refer Sec. 1.2, about the portability of your
program). It is referred to as an API (application programming interface), that
insulates the programmer from device differences and how they vary from one
system to another.

OpenGL was originally developed by Silicon Graphics Inc. (SGI) as a


multipurpose, platform independent graphics API. Since 1992, OpenGL
Architecture Review Board (ARB) has been looking after the development of
OpenGL. This board consists of some of the major graphics vendors and other
industry leaders such as Hewlett-Packard, IBM, NVIDIA, Sun Microsystems
and Silicon Graphics etc. In view of the fast development of graphics
hardware, ARB is committed to annual updates and the present version of
OpenGL is 3.0. OpenGL is now widely used in CAD, virtual reality, scientific
visualization, flight simulation and video games.

Purpose of this Appendix is to give you a quick exposure to graphics


programming in C using OpenGL and make you acquainted with basic
structure of a graphics program using OpenGL. We do not intend to give here a
complete introduction to OpenGL as we have already incorporated the required
details in the units at various places.

Objectives
After reading this supplement, you should be able to
• outline the basics of OpenGL;
• draw 2D objects with specified fill colors;
111
Computer Graphics • use OpenGL transformation function for 2D and 3D geometric
transformations;
• use simple animation to objects to be displayed in the scene;
• write interactive programs using mouse and keyboard functions of
OpenGL.

1.2 A Brief Overview


As you know OpenGL is a 3D graphics application programmers interface
(API) to produce high-quality, color images of 3D objects (group of geometric
primitives) and images (bitmaps and raster rectangles). Remember that it is not
a programming language like C or Java. To give you an idea of what is
primarily possible with OpenGL, we list here a few basic operations that you
can perform with the help of OpenGL.
• Creating interactive applications which render high-quality color images
composed of 3D geometric objects and images.
• Specification (modelling) of an arbitrarily complex set of objects in 3D
space - creation of a 3D virtual world. This includes
 Object specifications --- In terms of drawing primitives.
 Relative positions of multiple objects defined by transformations.
 Coloring objects, specifying light sources and light direction.
 Specification of a virtual camera by which to view the 3D virtual
world.
 Projection to 2D display.

You will explore many more features of OpenGL later in this appendix.

When a program is executed, OpenGL does the following:


• Assembles the virtual world.
• Points the virtual camera at the world. This means setting up a view angle
or direction and the volume or a frustum which you would like to keep in
your scene.
• Projects the scene onto a 2D projection plane
• Performs the equivalent of spatial sampling and rasterization.

To be more specific on the portability of your program, part of your


application which does rendering is platform independent. However, in order
for OpenGL to be able to render, it needs a window to draw into. OpenGL is
not capable of opening windows or responding to interrupts from a mouse or
keyboard. Generally, this is controlled by the windowing system on whatever
platform you are working on. As OpenGL is platform independent, we need
some way to integrate OpenGL into each windowing system. Every windowing
system where OpenGL is supported has additional API calls for managing
OpenGL windows, color maps, and other features. These additional APIs are
platform dependent. For the sake of simplicity, we will use an additional
freeware library for simplifying interaction with windowing systems. This is
called GLUT (GL Utility Toolkit). GLUT is a library which makes writing of
112
OpenGL programs, regardless of windowing systems, much easier. The GLUT Appendix: OpenGL -
A Quick Start
libraries provide facilities to define and open windows and respond to mouse
and keyboard functions.

Finally we conclude this section by telling you something about the rendering
pipeline of OpenGL. OpenGL Pipeline has a series of processing stages in
order (see Fig.1). Two graphical information, vertex-based data and pixel-
based data, are processed through the pipeline, combined together and then
written into the frame buffer. Notice that OpenGL can send the processed data
back to your application.

Vertex Data per-Vertex Operations


Evaluators
and Primitive Assembly

Display List Per-fragment


Rasterization Operation
Pixel
Operations Texture Frame Buffer
Pixel Data Assembly

Fig. 1.

Display List: Because of its structure, OpenGL require lots of procedure calls
to render a complex object. To improve efficiency, OpenGL allows you to
generate an object, called a display list, into which OpenGL commands are
stored in an efficient internal format, which can be called back again in the
future.

Vertex Operations: Vertex and normal coordinates are transformed by


GL_MODELVIEW matrix (from object coordinates to eye coordinates). Also,
if lighting is enabled, the lighting calculation per vertex is performed using the
transformed vertex and normal data. This lighting calculation updates new
color of the vertex.

Pixel Transfer Operations: After the pixels from client's memory are
unpacked (read), scaling, bias, mapping and clamping are performed on the
data. These operations are called Pixel Operations. The transferred data are
either stored in texture memory or rasterized directly to fragments.

Primitive Assembly: After vertex operation, the primitives (point, line, and
polygon) are transformed once again by projection matrix. These primitives are
clipped against viewing volume clipping planes, changing from eye
coordinates to clip coordinates. After that, perspective division by w occurs and
viewport transform is applied in order to map 3D scene to window space
coordinates. Last thing to do in Primitive Assembly is culling test if culling is
enabled.

Texture Memory: Texture images are loaded into texture memory to be


applied onto geometric objects.

Rasterization: Rasterization is the conversion of both geometric and pixel data


into fragment. Fragments are a rectangular array containing color, depth, line
width, point size and antialiasing calculations.
113
Computer Graphics Fragment Operation: It is the last process to convert fragments to pixels onto
frame buffer. The first process in this stage is texture generation. A texture
element is generated from texture memory and it is applied to the each
fragment. Then fog calculations are applied. After this a variety of different
fragment tests are applied. Finally, blending, dithering, logical operation and a
few more operations are performed and actual pixel data are stored in frame
buffer.

OpenGL as a State Machine

OpenGL is a state machine. You put it into various states (or modes) that
remain in effect until you change them. For example, the current color is a state
variable. Suppose you set the current color to white. Every object is then
drawn with white color until you set the current color to something else. There
are many such state variables that OpenGL maintains. Another example that
you might be using in your codes quite often would be point size. You can take
it to be one pixel thick or it can be thicker with more pixels.

1.3 HOW TO INSTALL OPENGL?


If you are using Window XP, NT or later versions, OpenGL is automatically
installed with your video driver. Since you also want to program in OpenGL,
you need to get some extra OpenGL libraries so that your programs will
compile. You can download information for gl and glut libraries from the
official website of OpenGL

http://www.opengl.org/resources/libraries/glut.html
or,
http://www.xmission.com/~nate/glut.html

Your library files in MS Windows-

If you are working in Visual Studio 6.0 IDE, then


1. Copy the glut.h header file in c:\program files\microsoft visual
studio\vc\include\gl location
2. Copy the glut.lib file in c:\program files\microsoft visual studio\vc\lib
location
3. Copy the glut32.lib file in c:\program files\microsoft visual studio\vc\lib
location
4. Copy the glut32.dll file in c:\windows\system32

If your system has Visual Studio 2005 , then you may try this.
1. Copy the glut.h header file in C:\Program Files\Microsoft Visual Studio
8\VC\PlatformSDK\Include location
2. Copy the glut.lib file in C:\Program Files\Microsoft Visual Studio
8\VC\PlatformSDK\Lib location
3. Copy the glut32.lib file in C:\Program Files\Microsoft Visual Studio
8\VC\PlatformSDK\Lib location
114 4. Copy the glut32.dll file in c:\windows\system32
OpenGL Installation on Linux Appendix: OpenGL -
A Quick Start

Installations of all kinds on Linux are very much dependent on distribution. If


you refer to your distribution's packages, installation may become a bit easier.
For example, on Debian-based distributions (with apt-get or equivalent
installed), following commands could be used to install the header files of
OpenGL libraries.

sudo apt-get update


sudo apt-get install libgl1-mesa-dev

Headers compatible with OpenGL are available from the Mesa3D project. If
your distribution does not contain development files for the Mesa3D project,
you may take help of Mesa3D that comes equipped with the usual installation
procedure.

./configure
make
make install

However, take care of conflicting OpenGL libraries. It may happen that Mesa's
software implementation overrides your distribution's libraries or manually
installed libraries.

The headers will be installed to [install_root]/include/GL - on Debian systems,


this is /usr/local/include/GL when compiled from source or /usr/include/GL
when installed from a pre-built package. Official OpenGL headers are available
from SGI, however, they have been superseeded by their upgrades.

Finally, the following url is useful for setting up OpenGL on any platform.

http://www.polytech.unice.fr/~buffa/cours/synthese_image/DOCS/Tutoriaux/N
ehe/lessons.htm

1.4 YOUR FIRST PROGRAM USING OPENGL


Let us begin by a simple C program which illustrates how you open a window
and specify its position and size. You need to structure your program as
follows:

• Initializing the window: Call the following function to initialize the


GLUT library.
glutInit(&argc, argv);

Its arguments should be the same as that of your main() function.

Now choose the type of window that you need for your application and
initialize it.

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);

This helps in initializing the graphics display mode (of the GLUT library)
to use a window with RGB buffers for color and with a single buffer for
display. Other options are also available. For example, you may use
115
Computer Graphics GLUT_DOUBLE for using a double buffer. In animation programs, it is
advisable to use double buffer. For complete information on various
options available, you may log on to
http://glprogramming.com/red/appendedixd.html or refer to the book [1],
mentioned at the end of this Study Guide that is also called Red Book.

glutInitWindowPosition (x, y);

specifies the window position at (x,y) pixel location. This means, the
window is x pixels to the right and y pixels down the top left corner of
the display screen.
glutInitWindowSize (w, h);

specifies the window size to be h units high and w units wide. You may
choose height and width as per your program's specifications and object
size.
glutCreateWindow(“A Rectangle”);

creates an OpenGL enabled window.

• State Initialization: Initialize any OpenGL state that you don’t want to
change in every frame of your program. This might include many states
such as background color, positions of light sources, texture maps etc.
For example, you would need to specify the RGB component of
background color to be used when clearing the color buffer using the
following function.

glClearColor(0.0f, 0.0f, 1.0f,1.0f);

Last argument is transparency factor.

glClear(GL_COLOR_BUFFER_BIT);

clears the window with current clearing color.

• Register Callback Functions: A callback function is an executable code


that is passed as an argument to other code. You need to register the
callback functions that you will need in you main program. Then GLUT
calls these functions when a certain sequence of events occur, like a user
input through mouse or the window needing to be refreshed.

The most important callback function is the following which renders your
scene.
glutDisplayFunc(display);

Here display() is the function you will write to create your objects.
The program Blank.c displays nothing, except the blank window. This
is because your display function does not involve any display function.
Use of

glFlush() ;

flushes every OpenGL command and buffers for display.


116
• Enter the main event processing loop: This is where your application Appendix: OpenGL -
A Quick Start
receives events, and starts the GLUT main processing loop.

glutMainLoop();

Let us now have a look at the complete C-code.

//Blank.c
#include <gl\glut.h>
/* Includes the OpenGL core header file. This file is required
by all OpenGL applications. */

//Initialize whatever you want to initialize here.


void init(void)
{
glClearColor(0.0f, 0.0f, 1.0f,1.0f);
}

//Called to draw scene


void display(void){
//clear window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);
// Flush drawing commands
glFlush();
}

//Main Loop
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
//No window size or position chosen. Program will use default
values.
glutCreateWindow("A Blank Window");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
} //Output will be a blank window

What you will get as an output will be the following.

Let us now modify our program to draw a square in the window. This time set
the background color to black. Color of the solid square by default will be
white. Note that there is a very little change in your display function and in
initialization.

//Square.c
#include <gl\glut.h>

117
Computer Graphics void init(void)
{
//Reset the coordinate system
glClearColor(0.0f, 0.0f, 0.0f,1.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, 500.0f, 0.0f, 500.0f, 1.0f, -1.0f);
}

//Called to draw scene


void display(void){
//clear window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);
glRectf(150.0f,150.0f,350.0f, 350.0f);
// Flush drawing commands
glFlush();
}

//Main Loop
void main(void)
{
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutCreateWindow("A Rectangle");
init();
glutDisplayFunc(display);
glutMainLoop();
}

The output looks as follows.

Note: You might have noticed that in the program we did not use some
functions and still the program could be executed. For example, we have not
used any arguments in the main function main( ). We have also not used
glutInit( ) here. The idea is to tell you that the program runs without these
functions and arguments also. However, for more efficient use of memory and
for a flawless performance of your program, it is advisable to make use of these
functions and arguments.

For plotting points you can use the following code and add it to your display
function.

glBegin(GL_POINTS);
glVertex3f(100.0f, 150.0f, 150.0f);
glVertex3f(200.0f, 150.0f, 200.0f);
glEnd() ;

118
There are a number of primitives for object modelling and rendering the scene. Appendix: OpenGL -
A Quick Start
You are advised to visit the official website of OpenGL to see the reference
manual for more information on drawing and other primitives.

Window Reshape Function: Every program displaying its output on window


uses a reshape function that indicates what action is to be taken when the
window is resized. This function has the following syntax.

glutReshapeFunc(void (* func)(int w, int h));

The function allows registration of a callback function that has to be called


when the window is resized. As an example of a callback function, we give the
following function reshape( ).

void reshape( GLsizei w, GLsizei h)


{ //Prevent divide by zero; w = width, h = height of window
if(h==0) h = 1;
//Set viewport to window dimension
glViewport(0,0,w,h);
//Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Adjust clipping volume with appropriate proportions
if( w<=h)
glOrtho( 0.0f, 250.0f, 0.0f, 250.0f*h/w, 1.0, -1.0);
else
glOrtho( 0.0f, 250.0f*w/h, 0.0f, 250.0f, 1.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

Then register the callback function

glutReshapeFunc(reshape);

in your main function to get the desired effect.

1.5 OPENGL FUNCTIONS, CONSTANTS, AND


DATA TYPES

Naming Conventions

Function names in the basic OpenGL library begin with the letters gl, and each
component word within a name has its first letter capitalized. For example-
glClear(), glBegin(). Fig. 2 for the glVertex*( ) function on the next page may
help you understand better the general naming conventions in gl and glut
libraries.

119
Computer Graphics Root command
gl Library

glVertex3fv( . . . )

Data type v – vector


2 – (x, y) Omit v for scalar
3 – (x, y, z) b – byte forms
4 – (x, y, z, w) ub – unsigned byte
Used only when the
s – short
data
No. of arguments I – int
is in vector form
ui - unsigned int
f – float
d - double

Fig. 2.

There are certain functions which require arguments that are constant
specifying a parameter name, a value for a parameter, a particular mode, etc.
All such constants begin with the letters GL, component words in the constant
are written in capital letters, and the underscore " _ " is used as a separator
between the words. For example, we have used GL_RGB and
GL_COLOR_BUFFER_BIT in our earlier program.

For making the program platform independent and for fast processing of
various routines, OpenGL has defined its own data types which are as given in
Table-1 below.
Table-1

Suffix Data Type C/C++ type OpenGL type name


b 8-bit int signed char GLbyte
s 16-bit int short GLshort
i 32-bit int int or long GLint, GLsizei
f 32-bit float float GLfloat, GLclampf
d 64-bit float double GLdouble, GLclampd
ub 8-bit unsigned no. unsigned char GLubyte, GLboolean
us 16-bit unsigned no. unsigned short GLushort
ui 32-bit unsigned unsigned int or GLuint, GLenum,
number unsigned short GLbitfield

In addition to the basic, or core, library of functions, a set of "macro" routines


that use core functions are available in the OpenGL Utility Library (GLU).
These routines provide methods for setting up viewing projection matrices,
describing complex objects with line and polygon approximations, surface
rendering, and other complex tasks. In particular, GLU provides methods for
displaying quadrics using linear-equation approximations.

OpenGL Colors and Display Modes

OpenGL colors are typically defined using RGB (red, green, blue) components
120 and a special A (or alpha) component. There are various ways in which you
could interpret A depending on the context (especially with reference to Appendix: OpenGL -
A Quick Start
transparency and color blending). Usually A = 1 when no special effects are
desired. We have used the function glutInitDisplayMode(unsigned int
mode) for setting up display mode. The mode is the logical-OR denoted by "x
| y" with various choices of x and y from the following:

GLUT_RGB for RGB colors, GLUT_RGBA for RGBA colors and


GLUT_INDEX for using color-mapped colors (not recommended) and
GLUT_SINGLE for single-buffering, GLUT_DOUBLE to allow double-
buffering (for smooth animation). Further you can use GLUT_DEPTH for
depth buffering for hidden surface removal.

Finally a brief discussion about the projection matrices. Fig. 3 gives you an
idea about the pipeline of transformations that you need to apply to render a 3D
scene. Remember that OpenGL is a 3D graphics standard and treats every
object as a 3D object. If the object is 2D, you can simply define that as a 3D
object sitting in the plane z = 0.

ModelView Projection Perspective Viewport


Point Matrix Matrix Normalization Transformation
Clipping

Standard Eye Normalized Window


coordinates coordinate Device coordinates
s coordinates

Fig. 3.

When you study 3D geometric and projection transformations in your


Computer Graphics course, you will be able to appreciate better this pipeline.
Because of this pipeline, you need to introduce the following callback
functions in your program.

glMatrixMode(GL_PROJECTION);
//Specifies that the current matrix is prjection
matrix
glLoadIdentity();
//replace the current matrix with the identity
matrix
glOrtho(0.0f, 500.0f, 0.0f, 500.0f, 1.0f, -1.0f);
/* Sets / modifies the clipping volume extents
for orthographic projection. Parameters specify
left, right, bottom, top, near, far extents in
the order */

For more details, you are advised to refer to Unit 5, Secs. 5.3-5.5 of this Study
Guide.

Some Output Primitives

You can use some of the following output primitives of OpenGL to practice
more on OpenGL programming.

121
Computer Graphics GL_POINTS: set of points

GL_LINES: set of line segments (not connected)

GL_LINE_STRIP: chain of connected line segments

GL_LINE_LOOP: closed polygon (may self intersect)

GL_TRIANGLES: set of triangles (not connected)

GL_TRIANGLE_STRIP: linear chain of triangles

GL_TRIANGLE_FAN: fan of triangles (joined to one point)

GL_QUADS: set of quadrilaterals (not connected)

GL_QUAD_STRIP: linear chain of quadrilaterals

GL_POLYGON: a convex polygon

1.6 OPENGL TRANSFORMATION FUNCTIONS


As already discussed, OpenGL treats every thing as 3D. Hence all the
transformations that are defined in OpenGL are 3D in nature. For using them in
2D applications, you simply need to ignore the third dimension parameter. For
example, following function translates the given object by (1, 1) in 2D, since
we have chosen the third parameter to be zero.

glTranslatef(1.0f, 1.0f, 0.0f);

Similarly, rotation about the origin in 2D is essentially the same as 3D rotation


about z-axis. Hence

glRotatef(45, 0.0f, 0.0f,1.0f);

will rotate the object about z-axis by an angle of 45 degrees around the origin.
Similarly, you can use OpenGL scaling function glScale*( ) for 2D
transformations. Following example of display function will help you
understand how rotation and scaling of a square have been performed with
respect to a pivot point (0.5, 0.5)

void myDisplay ( void ) {


glClear ( GL_COLOR_BUFFER_BIT );
// Set display color as green
glColor3f(0.0, 1.0, 0.0);
//scaling and rotation with (0.5,0.5) as the pivot point
//rotate upto 30 degree with an increment of 5
for(float angle=0; angle <30; angle=angle + 5)
{
glTranslated(-0.5f, -0.5f, 0.0f);
glScaled(0.7,0.7,10);
glRotated( angle, 0.0, 0.0, 1.0);
glTranslated(0.5f, 0.5f, 0.0f);
glBegin(GL_LINE_LOOP);
glVertex3f(-0.5, -0.5, 0.0);
glVertex3f(1.0, -0.5, 0.0);
122
glVertex3f(1.0, 1.0, 0.0); Appendix: OpenGL -
glVertex3f(-0.5, 1.0, 0.0); A Quick Start
glEnd();
}
glFlush();
}

To see the effect, replace the display function of one of your previous c-
program code with the above and you will see the following output on the
display window.

Unit 5 gives an introduction to 3D transformations with a brief decription of


OpenGL 3D transformations.

1.7 ANIMATION
OpenGL provides good support for animation design. Here we give a simple
example code showing the animation for two triangles. The executed code
displays falling triangles.
#include <gl/glut.h>
#include <math.h>

//Initialize triangles' position


GLfloat xx=100.0f;
GLfloat yy=100.0f;

//y direction decrement


GLfloat ystep =-5.0f;

//Keep track of window's changing width and height


GLfloat w;
GLfloat h;

//Display the scene


void myDisplay(void)
{
//Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);

// Set current drawing color to white


glColor3f(1.0f,1.0f,1.0f);

123
Computer Graphics //Draw a filled triangle with current color
glBegin(GL_TRIANGLES);
glVertex2f(xx,yy);
glVertex2f(xx+50,yy);
glVertex2f(xx+25,yy+25);
glEnd();
// Change color
glColor3f(0.0f,1.0f,0.0f);
// Draw another triangle 25 units away in x direction
// and 25 units down in y direction
glBegin(GL_TRIANGLES);
glVertex2f(xx+50,yy-10);
glVertex2f(xx+100,yy-10);
glVertex2f(xx+75,yy+15);
glEnd();
//Flush drawing commands and swap
glutSwapBuffers();
}

//Idle function-when system is idle/no user input/action

void TimerFunction(int value)


{
//If triangles go down the window, lift them up
if(yy < 0)
yy = 250+yy;

//Slide the trinagles down


yy=yy+ystep;

//Redraw the scene with changed coordinates


glutPostRedisplay();
glutTimerFunc(100,TimerFunction,1);
}

void reshape(GLsizei w, GLsizei h)


{
if(h==0) h=1;
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Preserve the proportions in changing window
if(w<=h){
w=250.0f*h/w;
h=250.0f;
}
else
{
w=250.0f*w/h;
h=250.0f;
}
glOrtho(0.0f,w,0.0f,h,1.0f,-1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void myInit(void)
{
glClearColor(0.0f,0.0f,1.0f,1.0f);
}

void main(void)
{
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutCreateWindow("Rotate");
124 glutDisplayFunc(myDisplay);
glutReshapeFunc(reshape); Appendix: OpenGL -
glutTimerFunc(100,TimerFunction,1); A Quick Start
myInit();
glutMainLoop();
}

A snapshot of the output is shown below.

A few words about the functions that we have used in making this animation.

void glutPostRedisplay(void) ;

This function tells GLUT that the window needs to be repainted with current
changes. So if you need to re-draw the scene with changes, call this function.

void glutSwapBuffers(void) ;

This function flushes the OpenGL commands and swaps the buffer, in case you
have given the option of double buffer ( GLUT_DOUBLE ) in your code. If
double buffer is not used, then also OpenGL commands are flushed.

void glutTimerFunc(unsigned int m, (*func)(int value), int


value);

This function registers a callback function func that should be called after m
milliseconds have elapsed. The integer value is the user specified value that is
passed to the callback function. Most of the OpenGL implementations provide
double-buffering. When one is being displayed, the other is getting prepared
for display. When the drawing of a frame is complete, the two buffers are
swapped, so that one that was being viewed now becomes available for
drawing, and vice versa.

1.8 MOUSE AND KEYBOARD FUNCTIONS


In order to make your program interactive, you can effectively use the mouse
and keyboard with the help of OpenGL mouse and keyboard functions. Some
of the functions that are frequently used in interactive programs are as follows:

glutMouseFunc(mouseFunc);
This function allows you to link a mouse button with a
function that is invoked when a mouse button is pressed or
released. Here mouseFunc is the name of the function that is
invoked on mouse event.
125
Computer Graphics
glutKeyboardFunc(keyFunc);
This function specifies a function that is to be executed when a
particular key character is selected. This function can also
return the current mouse position in window coordinates.

glutMotionFunc(motionFunc);
This function specifies a function that is to be executed when a
mouse moves within the window while one or more buttons
are pressed.

You can try the following piece of code to understand how these functions
work.

//button = mouse button, action can be pressed or released


// x, y indicate mouse position

void mouseFunc( GLint button, GLint state, GLint x, GLint y)


{
if( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
glRectf(x, h- y, x+50, h -(y+50)); // h is window height
else
if ( button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{ glBegin(GL_TRIANGLES);
glVertex2i(x, 250 - y);
glVertex2i(x+50, 250 - y);
glVertex2i(x+25, 250 -(y+25));
glEnd();
}
glFlush( );
}

The above function is required to be registered in your main program using the
following command.

glutMouseFunc(mouseFunc);

Similarly, a keyboard function example is given below.

void keyFunc(GLubyte key, GLint x, GLint y)


{
GLint mouse_x = x;
GLint mouse_y = h - y; //h is the window height
switch(key)
{
//Plot rectangle
case 'r':
glRectf(mouse_x, mouse_y, mouse_x+50, mouse_y+50);
break;
// Plot triangle
case 't':
glBegin(GL_TRIANGLES);
glVertex2i(mouse_x, mouse_y);
glVertex2i(mouse_x+50, mouse_y);
glVertex2i(mouse_x+25, mouse_y + 25);
glEnd();
break;
default:
126 break;
} Appendix: OpenGL -
A Quick Start
glFlush( );
}

The above callback needs to be registered in your main function as follows.

glutKeyboardFunc(keyFunc);

This gives a quick introduction to OpenGL primitives for graphics support.


OpenGL has a vast range of functions for modelling, rendering, animation and
image processing. For detailed study on OpenGL, you are advised to refer to
the following books/url.

1. Dave Shreiner, Mason Woo, Jakie Neider and Tom Davis, OpenGL
Programming Guide: The Official Guide to Learning OpenGL, Fifth
Edition, Addison Wesley, 2006.

2. Richard S. Wright, Jr., OpenGL Super Bible, Second Edition, Techmedia,


2007.

3. www.opengl.org/ (Official site of OpenGL).

127

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy