Sei sulla pagina 1di 34

Computer Graphics

Lecture # 2: Introduction Of
OpenGL
BSE
Joddat Fatima
Joddat.fatima@gmail.com
Department of C&SE
Bahria University Islamabad
1
What Is OpenGL?

OpenGL is designed as a streamlined, hardware-independent interface to be


implemented on many different hardware platforms.

To achieve these qualities, no commands for performing windowing tasks or


obtaining user input are included in OpenGL; instead, you must work
through whatever windowing system controls the particular hardware you're
using.

OpenGL doesn't provide high-level commands for describing models of three-


dimensional objects. Such commands might allow you to specify relatively
complicated shapes such as automobiles, parts of the body, airplanes, or
molecules.

With OpenGL, you must build up your desired model from a small set of
geometric primitives - points, lines, and polygons.
2
3
GL Utility Toolkit (GLUT)

OpenGL

is window system independent

Concerned only with drawing

No window management functions (create, resize, etc)

Very portable

GLUT:

Minimal window management: fast prototyping

Interfaces with different windowing systems

Allows easy porting between windowing systems


4
GL Utility Toolkit (GLUT)

No sliders

No dialog boxes

No menu bar, etc

To add them, need other API:


GLUT, the OpenGL Utility Toolkit

OpenGL contains rendering commands but is designed to be


independent of any window system or operating system.

It contains no commands for opening windows or reading events


from the keyboard or mouse.

Unfortunately, it's impossible to write a complete graphics


program without at least opening a window, and most
interesting programs require a bit of user input or other
services from the operating system or window system.
5
GLUT, the OpenGL Utility Toolkit

OpenGL drawing commands are limited to those that generate simple


geometric primitives (points, lines, and polygons), GLUT includes
several routines that create more complicated three-dimensional
objects such as a sphere, a torus, and a teapot.

This way, snapshots of program output can be interesting to look at.


(Note that the OpenGL Utility Library, GLU, also has quadrics
routines that create some of the same three-dimensional objects as
GLUT, such as a sphere, cylinder, or cone.)

GLUT may not be satisfactory for full-featured OpenGL applications,


but you may find it a useful starting point for learning OpenGL.
6
Window Management
Five routines perform tasks necessary to initialize a window.

glutInit(int *argc, char **argv) initializes GLUT and processes any command line
arguments (for X, this would be options like -display and -geometry). glutInit()
should be called before any other GLUT routine.

glutInitDisplayMode(unsigned int mode) specifies whether to use an RGBA or


color-index color model. (If you're working in color-index mode, you'll want to load
certain colors into the color map; use glutSetColor() to do this.)

For window to have an associated depth, stencil, and/or accumulation buffer. If you
want a window with double buffering, the RGBA color model, and a depth buffer,
you might call glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|
GLUT_DEPTH).
7
Window Management

glutInitWindowPosition(int x, int y) specifies the screen


location for the upper-left corner of your window.

glutInitWindowSize(int width, int size) specifies the size,


in pixels, of your window.

int glutCreateWindow(char *string) creates a window


with an OpenGL context. It returns a unique identifier for
the new window. Be warned: Until glutMainLoop() is
called, the window is not yet displayed.
8
The Display Callback
glutDisplayFunc(void (*func)(void)) is the first and most
important event callback function you will see. Whenever
GLUT determines the contents of the window need to be
redisplayed, the callback function registered by
glutDisplayFunc() is executed. Therefore, you should put
all the routines you need to redraw the scene in the display
callback function.
If your program changes the contents of the window,
sometimes you will have to call glutPostRedisplay(void),
which gives glutMainLoop() a nudge to call the registered
display callback at its next opportunity.
9
Running the Program
The very last thing you must do is call
glutMainLoop(void). All windows that have been
created are now shown, and rendering to those
windows is now effective. Event processing begins,
and the registered display callback is triggered.
10
intro1.cpp:
A Simple OpenGL Program

Now we will take a close look at an


OpenGL/GLUT program (intro1.cpp).

First a general overview.

Then each section of the program, in detail.

Lastly, some comments about philosophy.


11
intro1.cpp:
Overview

3 functions: main, init, display

Function main

Does initialization

Tells GLUT about display function

Turns control over to GLUT

Function init

Called by main to initialize GL options

Function display

Called when something needs to be drawn

Called only by GLUT


12
intro1.cpp:
Beginning
// intro1.cpp
// A simple OpenGL/GLUT program

Put comments like this on all programs for this class and
every other program you write for the rest of your
life.
#include <GL/glut.h> // GLUT stuff

Include this in all GLUT programs.

There are OpenGL headers, too (primarily <GL/gl.h>);


they are automatically included by glut.h.
13
intro1.cpp:
Function main [1/4]
int main(int argc, char ** argv)
{
// Initialize OpenGL/GLUT
glutInit(&argc, argv);

Above is always the same.

argc, argv come from Unix command-line conventions.


glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

Main GLUT display configuration call

One parameter: multiple options bitwise-ored together.

GLUT_SINGLE means 1 color buffer (stores the color of a pixel).

GLUT_RGB means no color LUT.

Can allocate other buffers: GLUT_DEPTH for a depth buffer.


14
intro1.cpp:
Function main [2/4]
// Make a window
glutInitWindowSize(300, 300);
glutInitWindowPosition(50, 50);
glutCreateWindow("CS4603 Computer Graphics");

Specify window size (x,y), position (x,y), and title.

OS may ignore these and put window wherever it feels like.


15
intro1.cpp:
Function main [3/4]
// Initialize GL states & register callbacks
init();
glutDisplayFunc(display);

Tell GLUT what function to call to draw window contents.

display is a callback; needs to be registered with GLUT.

Other callbacks can be registered using functions like

glutKeyboardFunc (for keypresses)

glutMouseFunc (for mouse events)

glutReshapeFunc (for when the user resizes the window)

glutIdleFunc (for when nothing is happening)

and others.
16
intro1.cpp:
Function main [4/4]
// Do something
glutMainLoop();
return 0;
}

Turn control over to GLUT.

GLUT handles high-level flow of control from now on; when


something needs to be done, GLUT calls the appropriate callback.

return 0; is just to keep the compiler happy.


17
intro1.cpp:
Function init [1/2]
void init()
{
glClearColor(0.9, 0.7, 0.8, 0.0);

Here we set various GL states.

The first state to set is the background color.

Set to light pink: 90% red, 70% green, 80% blue.

4th parameter is alpha.

Alpha is used for many things; most common use is transparency.

Alpha not used in this program, but it is a required parameter.


glLineWidth(3.0);

Another GL state: width of lines in pixels (default value = 1).


18
intro1.cpp:
Function init [2/2]
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

In OpenGL, drawing data is sent through a pipeline, in which transformations


are applied to vertex coordinates. These transformations are stored as 44
matrices.

Here, we set up the matrix to do the projection onto the screen.

What is important to know now is that the first 4 parameters of glOrtho set
up a coordinate system for the window:

x-coordinate of left side

x-coordinate of right side

y-coordinate of bottom

y-coordinate of top
19
intro1.cpp:
Function display [1/4]
void display()
{
glClear(GL_COLOR_BUFFER_BIT);

The first thing to do when displaying is to clear the buffer.

glClear sets every pixel in the color buffer to the color specified
with glClearColor.

Can clear other buffers (if they were allocated by the


glutInitDisplayMode call).
20
intro1.cpp:
Function display [2/4]
glColor3d(0.1, 0.1, 0.9);

Sets the color of upcoming vertices.

Color is another GL state.

glColor can take several forms with different types of


parameters.

3d means 3 GLdoubles.

In general, the function name is assembled as


gl + command + # params + type

E.g., glColor4f would take 4 GLfloats (red, green, blue, alpha).


glColor3dv would take a vector (array) of 3 GLdoubles.
21
intro1.cpp:
Function display [3/4]
glBegin(GL_LINES);
glVertex2d(0.1, 0.4);
glVertex2d(0.1, 0.6);
glVertex2d(0.3, 0.6);
glVertex2d(0.3, 0.4);
glEnd();

Specifying the coordinates of actual things to draw is done between glBegin and
glEnd.

glVertex call gives coordinates; GL_LINES tells how to use them.

Coordinate system was specified by the glOrtho call.

GL_LINES is a GL primitive; it means take vertices in pairs and use them as


endpoints of line segments.

glVertex is another function with several forms.

Indentation between glBegin and glEnd is helpful (but, of course, not required).
22
intro1.cpp:
Function display [4/4]
glBegin(GL_LINE_LOOP);
glVertex2d(0.5, 0.4);
glVertex2d(0.4, 0.2);
glVertex2d(0.6, 0.2);
glEnd();

GL_LINE_LOOP is another GL primitive; it means to draw an outline polygon that


is closed at the ends (first joined to last).
glFlush();
}

glFlush says start drawing now.

Another possibility is glFinish: start and wait until done.

In this class, end your display functions with glFlush.


23
OpenGL Philosophy [1/3]

For a program that does so little, intro1.cpp


uses lots of GL/GLUT function calls (40 of them).

This is typical; OpenGL is function-call intensive.


24
OpenGL Philosophy [2/3]

Graphical objects often have many


options (for lines: endpoints, width,
color, smoothing, cap style, dashed style,
etc.).

How should all these options be


specified? Two philosophies:
1. Throw everything in a big struct (MS D3D,
Apple QuickDraw to some extent).
2. Use lots of function calls (OpenGL).
25
OpenGL Philosophy [3/3]

Advantages to function-call-intensive
approach to API design:

Easy to learn and use.

Unused options can be ignored.

API is easy to extend.

Disadvantages:

A bit slower, due to function-call overhead.

The solution to the speed problem is


display lists (OpenGL commands stored in
large data structure for fast drawing).
26
gluOrtho2D()
The gluOrtho2D() routine puts the origin, (0, 0), all the
way in the lowest, leftmost square, and makes each square
represent one unit. Now when you render the points, lines,
and polygons in the rest of this chapter, they will appear on
this paper in easily predictable squares. (For now, keep all
your objects two-dimensional.)

Coordinate System Defined by w = 50, h = 50

27
28
A View of OpenGL Code

Because you can do so many things with the OpenGL graphics


system, an OpenGL program can be complicated.

The basic structure of a useful program can be simple: Its tasks are
to initialize certain states that control how OpenGL renders and to
specify objects to be rendered.

Before you look at some OpenGL code, let's go over a few terms.

Rendering, which you've already seen used, is the process by which


a computer creates images from models. These models, or objects,
are constructed from geometric primitives - points, lines, and
polygons - that are specified by their vertices.
29
A View of OpenGL Code

The final rendered image consists of pixels drawn on the screen; a pixel
is the smallest visible element the display hardware can put on the
screen.

Information about the pixels (for instance, what color they're supposed
to be) is organized in memory into bitplanes.

A bitplane is an area of memory that holds one bit of information for


every pixel on the screen; the bit might indicate how red a particular
pixel is supposed to be.

The bitplanes are themselves organized into a framebuffer, which holds


all the information that the graphics display needs to control the color
and intensity of all the pixels.
30
White Rectangle on a Black Background (Example)
Now look at what an OpenGL program might look like. Which
renders a white rectangle on a black background, as shown in
Figure.

31
Chunk of OpenGL Code
#include <>
main() {
glClearColor (0.0, 0.0, 0.0, 0.0); \\What color window will be cleared to
glClear (!"C#!#$"%&''($"%)*); \\Window to blac+
glColor,- (..0, ..0, ..0); \\Color u/e -or drawing ob0ect/
gl#rtho(0.0, ..0, 0.0, ..0, 1..0, ..0);
\\ 23eci-ie/ the coordinate /4/tem #3en! a//ume/ a/ it draw/ the -inal
\\ image and how the image get/ ma33ed to the /creen.
gl%egin(!"5#!6#7); 88 9e-ine the ob0ect to be drawn
gl:erte;,- (0.<=, 0.<=, 0.0);
gl:erte;,- (0.>=, 0.<=, 0.0);
gl:erte;,- (0.>=, 0.>=, 0.0);
gl:erte;,- (0.<=, 0.>=, 0.0);
gl(nd();
gl'lu/h();
88 en/ure/ that the drawing command/ are actuall4 e;ecuted rather than
88/tored in a buffer awaiting additional #3en! command/
?
32
Orthographic Projection
void glOrtho(GLdouble left, GLdouble right, GLdouble bottom,
GLdouble top, GLdouble near, GLdouble far);

Creates a matrix for an orthographic parallel viewing
volume and multiplies the current matrix by it. (left, bottom,
-near) and (right, top, -near) are points on the near clipping
plane that are mapped to the lower-left and upper-right
corners of the viewport window, respectively. (left, bottom, -far)
and (right, top, -far) are points on the far clipping plane that
are mapped to the same respective corners of the viewport.
Both near and far can be positive or negative.
33
34

Potrebbero piacerti anche