COMPUTER GRAPHICS
BY ATIF MUGHEES
Lecture No. 3
Department of Computer Science, National University of Computer & Emerging Science Islamabad, Pakistan
1
SOME GOOD REFERENCES
(1/2)
We have gone through a brief introduction to the field of computer graphics. The following references are worth looking into: 1. Hearn and Baker, Computer Graphics, Prentice Hall. 2. Foley and Van Dam, Introduction to Computer Graphics, Addison Wesley 3. Graphics Gems Five volumes
2
SOME GOOD REFERENCES
(2/2)
1.
2.
3.
Journals and Magazines for New Techniques SIGGRAPH (special interest group for graphics) annual proceedings (some 30,000 scientists and researchers meet in their annual gathering). IEEE (Institute of Electrical and Electronics Engineers) Computer Graphics and Applications ACM (association for Computing Machinery)
1.
Transactions on Graphics
3
OUR APPROACH
Computer graphics is mastered most quickly by doing it.
Write
and test programs that produce a variety of pictures. some variations see what happens and move towards drawing more complex scenes.
Start with the simple tasks
Try
GETTING STARTED
You need an environment consisting of
1.
2.
Hardware to display pictures (usually a CRT display generally called a screen) and A library of software tools that your program can use.
Establishes the display mode (to graphics) Setting up a coordinate system on the display
Initialization of the hardware
1.
2.
HISTORY
Silicon Graphics (SGI) revolutionized the graphics workstation by implementing the pipeline in hardware (1982) To access the system, application programmers used a library called IrisGL With IrisGL, it was relatively simple to program three dimensional interactive applications
OPENGL
The success of IrisGL lead to OpenGL (1992), a platform-independent API that was
Easy to use Close enough to the hardware to get excellent performance Focused on rendering Omitted windowing and input to avoid window system dependencies
OPENGL PORTABILITY
Portability
Different platforms (frame buffer, video cards, CPU, etc.) Operating system independent Can take code from one machine to another with minimal effort E.g. Quake on Linux
How it works?
E.g. glVertex3f()
Microsoft will provide their own .dll and .lib Linux will provide their own .dll and .lib
To be OpenGL compliant each platform must have a basic set of functions
OPENGL UI INTERFACING
OpenGL does not have UI capabilities
Dialog Boxes Windows Mouse Context Menu Event Mechanism
OpenGL is focused on Graphics only Use MFC, VB or GLUT for GUI handling
GLUT
OpenGL Utility Toolkit (GLUT)
Provides functionality common to all window systems
Open a window Mouse and Keyboard inputs Menus Event-driven
Code is portable but GLUT lacks the functionality of a good toolkit for a specific platform
No slide bars
LACK OF OBJECT ORIENTATION
OpenGL is not object oriented so that there are multiple functions for a given logical function
glVertex3f glVertex2i glVertex3dv
Underlying storage mode is the same Easy to create overloaded functions in C++ but issue is efficiency
INSTALLING OPENGL
OpenGL comes preinstalled with Windows 95/98/NT/2000. In your system directory C:\windows\system files glu32.dll C:\WINNT\system32\ or C:\windows\system32 files opengl32.dll
INSTALLING GLUT
Copy glut32.dll to the C:\windows\system directory (or C:\winnt\system32 if you are working on NT/2000). Copy glut32.lib to C:\Program Files\Microsoft Visual Studio\VC98\lib\ or to the equivalent lib directory where you have Visual C++ installed. Borland users should copy this lib-file to the lib directory of the Borland compiler. Copy the file glut.h to C:\Program Files\Microsoft Visual Studio\VC98\include\GL\ (or the corresponding Borland include\GL directory). Restart windows (very important) to enable the OS to load the glut32.dll and you should be all set.
COMPILING YOUR OPENGL CODE IN VISUAL C++
Specifying Link Libraries in Visual C++ To compile an OpenGL program in Visual C++ requires that you tell the linker where to find the OpenGL and GLUT library files. To shortcut things, you may also copy an existing .c/.cpp file into a project directory and double click on it to start Visual C++. Then go to Build to compile the file. Visual C++ will ask you if it should create a default workspace. Click OK. The file will compile, but you will likely get many link errors.
COMPILING YOUR OPENGL CODE IN VISUAL C++
You need to tell Visual C++ where to find the OpenGL libraries. Click "Settings" under the "Project" menu. Open up the Link tab. Now in the "Object/library Files" box, put in this list of .lib files:
opengl32.lib
glu32.lib glut32.lib
Build your code again (F7). Now you should not get any link errors and the code should compile and execute (CTRL-F5).
ADDING NEW SOURCE CODE FILES
Open File-New and pick "C++ Source File" name it whatever you like (for example, main.c) Look around for a FileView tab, It should be on the sidebar on your left If you can't find it, hit Alt+0 (Alt Zero) to bring it up. Double click the "main.c" file.
ADDING NEW SOURCE CODE FILES
Then add to the top of this file the lines: // Standard includes #include <stdlib.h> #include <stdio.h> #include <string.h> // string-related functions #include <time.h> // time-related functions #include <math.h> // math functions (sin, cos, etc.) // OpenGL includes #include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> Important: include <GL/glut.h> before all the other GL include files! It shouldnt matter, but under Windows it apparently does.
OPENGL FUNCTION FORMAT
EVENT LOOP
Note that the program defines a display callback function named mydisplay
Every glut program must have a display callback The display callback is executed whenever OpenGL decides the display must be refreshed, for example when the window is opened The main function ends with the program entering an event loop
Can have other callback functions as well
COORDINATE SYSTEMS THREE POSSIBILITIES
1. The entire screen is used for drawing
x increases to the right (100,50)
(1/3)
(150,75)
y inclrease donwards
(0,250)
22
COORDINATE SYSTEMS THREE POSSIBILITIES
2. A window-based system is used. Different rectangular windows of different sizes at various locations are supported. Initialization involves creating and opening a new window. A coordinate system is attached to each window. X inclreases to the right and y increases downwards X-Windows on Linux, Solaris, Ultrix etc
(2/3)
Windows Application Programming Interface (API) on Windows XP 23 Quick Drawn on Apple Macintosh system
COORDINATE SYSTEMS THREE POSSIBILITIES
3. A window-based system is used. Different rectangular windows of different sizes at various locations are supported. Initialization involves creating and opening a new window. A coordinate system is attached to each window. X increases to the right and y increases upwards
Any window based system using OpenGL
(3/3)
24
ELEMENTARY DRAWING TOOLS
These tools vary from system to system. setPixel(x,y,color) sets an individual pixel at location (x,y) with the color specified to color.
putPixel()
or drawPoint() could be alternatives
Line(x1,y1, x2,y2) draws a line between pixels at locations (x1,y1) and (x2,y2).
drawLine()
could be an alternative on some
system Some systems use moveto() and lineto() an analogy develop a whole tool the used of functions based on A programmer can adopted from kit of sophisticated pen plotters these
elementary drawing tools.
25
DEVICE INDEPENDENCE PROGRAMMING AND OPENGL
Device independent graphics programming means a uniform approach is made so that the same program could be compiled and run on a variety of environments with the guarantee to produce the same results, OpenGL offers such a tool. OpenGL provides an API (application programming interface), i.e. a collection of routines that a programmer can call, shielding the programmer from the hardware and software details of the system. OpenGL is most powerful when drawing images of complex three-dimensional (3D) scenes. It also works well for two-dimensional (2D) drawings which we will be looking into for the time being.
26
WINDOW-BASED PROGRAMMING
Most window-based programs are event-driven: a program responds to various events such as click of a mouse, pressing of a key on the keyboard or the resizing of the window. The systems maintains an event-queue which receives messages stating that certain event has occurred and deals with them on first come first served basis. The programs are generally written in terms of call-back functions: the function that is executed when a particular event takes place.
27
A SKELETON OF AN EVENT-DRIVEN PROGRAM USING OPENGL
void main() {
COMMENTS
initialize things create a screen window
glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard) ;
// An example main function. // Text in italics is pseudo code. // register the redraw function //register the reshape function // register the mouse action function // register the keyboard action function // enter the un-ending main loop
some other code here
glutMainLoop() }
All other call-back functions are defined here.
EVENT-DRIVEN PROGRAMMING
28
EXPLANATION
glutDisplayFunc(myDisplay): Here myDisplay is the function which is executed whenever the graphics window is redrawn. This happen when a window first opens, and when the window is exposed by another window off of it. glutReshapeFunc(myReshape): The function myReshape is called whenever the window is reshaped (its size is changed) glutMouseFunc(myMouse): The function myMouse is executed in response to a mouse event. glutKeyboardFunc(myKeyboard): This command registers the function myKeyboard with the event of pressing or releasing a key on the keyboard. glutMainLoop(): This functions makes the program to enter into an endless loop waiting for the event to occur.
29
OPENING A WINDOW FOR DRAWING
// appropriate #include go here. void main(int argc, char** argv) { glutInit(&argc, argv); // initialize the toolkit glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set the display mode glutInitWindowSize(640, 480); // set the window size glutInitWindowPosition(100, 150); // set the window position on screen // open the screen window glutCreateWindow(My first graphics program in opengl); // register the callback functions glutDisplayFunc(myDisplay); glutReshapeFunc(myReshape); glutMouseFunc(myMouse); glutKeyboardFunc(myKeyboard); myInit(); // some additional initialization as required glutMainLoop(); }
30
A COMPETE OPENGL PROGRAM TO DRAW THREE DOTS
In the next few slides, I present a complete OpenGL program to draw some dots on screen. This will be followed by an explanation of some of the functions that have been used in this program.
31
A COMPETE OPENGL PROGRAM TO DRAW THREE DOTS
#include <gl/Gl.h> #include <gl/glut.h> void myInit() // *************** myInit ************** { glClearColor(1.0, 1.0, 1.0, 0.0); // set white background color glColor3f(0.0, 0.0, 0.0); // set the drawing color glPointSize(4.0); // a dot will be 4 by 4 pixels glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 640.0, 0.0, 480.0); } void myDisplay(void) // *************** myDisplay **************** { glClear(GL_COLOR_BUFFER_BIT); // clear the screen glBegin(GL_POINTS); // draw three points glVertex2i(100, 50); glVertex2i(100, 130); glVertex2i(150, 130); glEnd(); glFlush(); // send all output to display }
32
A COMPETE OPENGL PROGRAM TO DRAW THREE DOTS
void main(int argc, char** argv) { glutInit(&argc, argv); // initialize the toolkit glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);//set the display mode glutInitWindowSize(640, 480); // set the window size glutInitWindowPosition(100, 150); //set the window position on screen // open the screen window glutCreateWindow(Dots in opengl); glutDisplayFunc(myDisplay); // register the redraw functions myInit(); // some additional initialization as required glutMainLoop(); }
33
EXPLANATION
The initial coordinate system for drawing
Dots in OpenGL
479
639
34
EXPLANATION
Output primitives line points, lines, polylines and polygons are defined in terms of one or more vertices. Such objects are drawn by passing a list of vertices. This list is defined within a pair of OpenGL function calls: glBegin() and glEnd(). We declare the types of the object through a library defined constant in glBegin argument list. glBegin(GL_POINTS); // draw three points glVertex2i(100, 50); glVertex2i(100, 130); glVertex2i(150, 130); glEnd();
Here GL_POINTS is a constant built-into OpenGL. Other constants are GL_LINES, GL_POLYGON etc.
35
OPENGL DATA TYPES
Suffix b Data Type 8-bit integer Typical C or C++ type signed char OpenGL type name GLbyte
s i
f d ub us ui
16-bit integer 32-bit integer
32-bit floating point 64-bit floating point 8-bit unsigned number 16-bit unsigned number 32-bit unsigned number
short int or long
float double unsigned char unsigned short unsigned int or unsigned long
GLshort GLint or GLsizei
GLfloat or GLclampf Gldouble or Glclampd GLubyte or GLboolean GLushort GLuint, GLenum, GLbitfield
36
OPENGL DATA TYPES
As an example, a function using suffix i expects a 32-bit integer, but your system might translate int as a 16-bit integer void drawDot(int x, int y) { glBegin(GL_POINTS); // draws a dot at (x, y) glVertex2i(150, 130); glEnd(); } A better option will be to use: void drawDot(GLint x, GLint y) { glBegin(GL_POINTS); // draws a dot at (x, y) glVertex2i(150, 130); glEnd(); }
37
THE OPENGL STATE
OpenGL keeps track of many state variables, such as
The current size of a point, The current color of a drawing The current background color
The value of a state variable remains active until a new value is given. The size of a point can be set with glPointSize(), which takes one floating point argument. If the argument is 3.0, the point is usually drawn as a square with 3 pixels on a side. The color of a drawn can be specified using glColor3f( red, green, blue); where the values of red, green and blue vary between 0.0 and 1.0. The background color is set with glClearColor( red, green, blue, alpha); where alpha specifies a degree of transparency. To clear the entire window to the background color, use glClear( GL_COLOR_BUFFER_BIT);
38
ESTABLISHING THE COORDINATE SYSTEM
We will discuss it in detail when we discuss windows, viewports and clipping. The myInit() function is a good place to set up the coordinate system. OpenGL performs routinely a large number of transformations. This is done using matrices.
gluOrtho2D()
function sets the transformation we need for a screen window of size 640 pixels by 480 pixels. 39
MAKING LINE DRAWINGS
Use GL_LINES as the argument to glBegin() and pass it the two endpoints as vertices.
glBegin(GL_LINES); glVertex2i(40, 100); glVertex2i(202, 96); glEnd();
If more than two vertices are specified between glBegin() and glEnd(), they are taken in pairs, and a separate line is drawn between each pair.
40
DRAWING DOT CONSTELLATIONS
Example 2.2.3 Simple Dot Plots
This example deals with learning the behaviour of some mathematical function f(x) as x varies. Suppose we have x
f ( x) e
cos(2 x)
where x varies from x=0 to x=4. To plot this function we sample it at a collection of equispaced xvalues and plot a dot at each coordinate pair (x, f(x)). Choosing a suitable increment, say 0.005, between consecutive xvalues, the basic process will run as follows: glBegin(GL_POINTS); for (GLdouble x=0; x<4.0; x += 0.005) glVertex2d(x, f(x)); glEnd(); glFlush
41
DRAWING DOT CONSTELLATIONS
Example 2.2.3 Simple Dot Plots
Problem:
1.
2.
The picture produced is impossibly tiny, because the values of x from 0 to 4 are mapped to only first four pixels at the bottom of the screen window. The negative values of f(x) lie below the window and are not visible. Scaling x: The first problem is solved if we scale x and then plot it. Consider a screen of width screenWidth, the scaled x values can be obtained as sx = x * screenWidth / 4.0; So for x = 0, sx = 0 and for x = 4.0, sx = screenWidth.
42
Solution:
1.
DRAWING DOT CONSTELLATIONS
Example 2.2.3 Simple Dot Plots
Solution:
2.
Note:
Scaling and Shifting y: The second problem is solved if we place the plot at the center of the screen window. Consider a screen of height screenHeight, the scaled and shifted y values can be obtained as sy = (y + 1.0)* screenHeight / 2.0; So for y = -1.0, sy = 0 and for y = 1.0, sy = screenHeight.
The conversion from x to sx and from y to sy are of form: sx = A x + B Affine sy = C y + D Transformations For properly chosen values of A, B, C and D. A and C are scaling coefficients and B and D are shifting coefficients.
43
DRAWING DOT CONSTELLATIONS
Example 2.2.4 Simple Dot Plot Complete Program
(1/2)
#include <math.h> #include <gl/Gl.h> #include <gl/glut.h> const int screenWidth = 640; // width of the screen window in pixels const int screenHeight =480; // height of the screen window in pixels GLdouble A, B, C, D; // scaling and shifting coefficients void myInit(void) { glClearColor(1.0, 1.0, 1.0, 0.0); // background color is set to white glColor3f(0.0, 0.0, 0.0); // drawing color is set to black glPointSize(2.0); // a dot is 2 by 2 pixels glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, (GLdouble)screenWidth, 0.0, (GLdouble)screenWeight); A = screenWidth / 4.0; B = 0.0 C = D = screenHeight / 2.0; }
44
DRAWING DOT CONSTELLATIONS
Example 2.2.4 Simple Dot Plot Complete Program (2/2)
void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT); // clear the screen glBegin(GL_POINTS); // draw the points for (GLdouble x=0; x<4.0; x += 0.005) { GLdouble func = exp(-x)*cos(2*3.14159265*x); glVertex2d( A*x + B, C*func + D ); } glEnd(); glFlush(); } void main(int argc, char **argv) { glutInit(&argc, argv); // initialize the toolkit glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode glutInitWindowSize(screenWidth, screenHeight); // set window size glutInitWindowPosition(100, 150); // set window position on screen glutCreateWindow(Dot Plot of a Function); glutDisplayFunc(myDisplay); // register display function myInit(); glutMainLoop(); // go for a perpeptual loop }
45