0% found this document useful (0 votes)
21 views49 pages

Chapter 3

Uploaded by

deti1234erbamo
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)
21 views49 pages

Chapter 3

Uploaded by

deti1234erbamo
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/ 49

Computer Graphics

OpenGL
What is OpenGL?
• It is NOT a language.
• It is a Graphics Rendering API (Application
Programmer’s Interface) that is a set of function
with well defined interface.
• Whenever we say that a program is OpenGL-based
or OpenGL applications, we mean that it is written
in some programming language (such as C/C++ or
Java) that makes calls to one or more of OpenGL
libraries.
• OpenGL is Not Object-Oriented. OpenGL API
does not make use of features such as overloading
that are available in object-oriented languages. -> 2
Three View of OpenGL
• Programmer’s view
– Specifying a set of objects to render
– Describing properties of these objects
– Defining how these objects should be viewed
• State machine
– Keeps states that affects appearances of input ie.
States determines how the inputs are processed.
– Change state (such as color) by using state changing
functions
• OpenGL uses Rendering Pipeline Model
– Models -> Transformer -> Clipper -> Projector ->
Rasterizer -> Image
3
OpenGL API Functions
• OpenGL contains over 200 functions
– Primitive functions : define the elements (eg. A
point, line, polygon, etc)
– Attribute functions : control the appearance of
primitives (eg. colors, line types, light source,
textures.)
– Viewing functions : determine the properties
of camera. Transformation
– Windowing functions: not part of core OpenGL
– Other functions
4
Window Management
• OpenGL is meant to be platform
independent. i.e. OpenGL is window
and operating system independent.
• OpenGL contains a number of
functions for window management,
user interaction, and file I/O.
• Host environment is responsible for
window management.
5
OpenGL Division of Labor
• GL - “core” library of OpenGL that is
platform independent
• GLU - an auxiliary library that
handles a variety of graphics
accessory functions
• GLUT/AUX - utility toolkits that
handle window managements

6
Cont…
• Core OpenGL (GL): consists of
hundreds of commands, which begin
with a prefix "gl" (e.g., glColor,
glVertex, glTranslate, glRotate).
• The Core OpenGL models an object
via a set of geometric primitives -
point, line, and polygon.

7
Cont…
• OpenGL Utility Library (GLU): built
on-top of the core OpenGL to provide
important utitlities and more building
models (such as qradric surfaces).
• GLU commands start with a prefix
"glu" (e.g., gluLookAt, gluPerspective)

8
Cont..
• OpenGL Utilities Toolkit (GLUT):
provides support to interact with the
Operating System (such as creating a
window, handling key and mouse
inputs);
• and more building models (such as
sphere and torus).
• GLUT commands start with a prefix
of "glut" (e.g., glutCreatewindow,
glutMouseFunc). 9
Libraries and Headers
Library Name Library File Header File Note
OpenGL opengl32.lib (PC) gl.h “core”
-lgl (UNIX) library
Auxiliary library glu32.lib (PC) glu.h handles a
-lglu variety of
accessory
functions
Utility toolkits glut32.lib (PC) glut.h window
-lglut (UNIX) glaux.h managemen
glaux.lib (PC) ts
-lglaux (UNIX)
Learning OpenGL with
GLUT
• GLUT is a Window Manager (handles
window creation, user interaction,
callbacks, etc)
• Platform Independent
• Makes it easy to learn and write OpenGL
programs without being distracted by your
environment

11
Include Header files
Include the necessary header files in your code

#include <GL/gl.h> // “core”, the only thing is required


#include <GL/glu.h> // handles accessory functions
#include <GL/glut.h> // handles window managements

void main( int argc, char **argv )


{
…..
}
Link Libraries
Link the necessary Libraries to your code

• Link GL library
– Link opengl32.lib (PC), or -lgl (UNIX)
• Link GLU library
– Link glu32.lib (PC), or -lglu (UNIX)
• Link GLUT library
– Link glut32.lib (PC), or -lglut (UNIX)
Programming Convention :
OpenGL Data Types
To make it easier to convert OpenGL code
from one platform to another, OpenGL
defines its own data types that map to
normal C/C++ data types

GLshort A[10]; short A[10];


GLdouble B; double B;
Programming Convention :
OpenGL Data Types
OpenGL Data Type Representation As C Type
GLbyte 8-bit integer signed char
GLshort 16-bit integer short
GLint, GLsizei 32-bit integer long
GLfloat 32-bit float float
GLdouble 64-bit float double
GLubyte, GLboolean 8-bit unsigned integer unsigned char
GLushort 16-bit unsigned short unsigned short
GLunit, GLenum, GLbitfield 32-bit unsigned unsigned long
integer
Programming Convention :
OpenGL Function Naming
OpenGL functions all follow a naming convention
that tells you which library the function is from,
and how many and what type of arguments that
the function takes

<Library prefix><Root command><Argument count><Argument type>


Programming Convention :
OpenGL Function Naming
glColor3f(…)
library prefix root command # of argument type of arguments

gl means OpenGL f: the argument is float type


glu means GLU i: the argument is integer type
glut means GLUT v: the argument requires a vector
Programming Convention :
OpenGL Function Naming
• Multiple forms of OpenGL functions
to support the variety of data types
– glVertex3i(ix, iy, iz)
– glVertex3f(x, y, z)
– glVertex2i(ix, iy)
– glVertex2f(x, y)
– ..
– We shall use the notation glVertex*() to
refer to all the forms of the vertex
18
function
Basic OpenGL Coding
Framework
1. Configure GL (and GLUT) - Open window,
Display mode, ……
2. Initialize OpenGL state - background
color, light, View positions, ……
3. Register callback functions - Render,
Interaction (keyboard, mouse), ……
4. Event processing loop - glutMainLoop()

19
A Sample Program
void main (int argc, char **argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
1
glutCreateWindow (“My First Program");
myinit (); 2
glutDisplayFunc ( display );
glutReshapeFunc ( resize ); 3
glutKeyboardFunc ( key );
glutMainLoop (); 4
}
1: Initializing & Creating
Window
Set up window/display you’re going to use
void main (int argc, char **argv)
{
glutInit (&argc, argv); // GLUT initialization
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // display model
glutInitWindowSize (500, 500); // window size
glutCreateWindow (“My First Program"); // create window
……
}
GLUT Initializing Functions
• Standard GLUT initialization
void glutInit (int *argc, char ** argv)
• Display model
void glutInitDisplayMode (unsigned int mode)
–Define color model : GLUT_RGB or GLUT_INDEX
–Define buffering: GLUT_SINGLE | GLUT_DOUBLE
• Window size and position
void glutInitWindowSize (int width, int height)
void glutInitWindowPosition(int x, int y)
- top-left corner of the screen in pixel
• Create window
int glutCreateWindow (char *title);
2: Initializing OpenGL
State
Set up whatever state you’re going to use
void myinit(void)
{
glClearColor(1.0, 1.0, 1.0, 1.0); // background color
glColor3f(1.0, 0.0, 0.0); // line color
glMatrixMode(GL_PROJECTION); // followings set up viewing
//deals with matrices used by perspective,orthogonal transformation
glLoadIdentity();//reset current matrix back to its default state or
replace the current matrix with identity matrix
gluOrtho2D(0.0, 500.0, 0.0, 500.0);
glMatrixMode(GL_MODELVIEW);//deals with matrices used by
model view transformation
Event Loops and Callback
Functions
• Interactive programs react to the
events such as mouse or keyboard
events and window events.
• Callback Function - Routine to call when
something happens (eg. window resize, redraw,
user input, etc)

• GLUT uses a callback mechanism to do


its event processing
GLUT Callback Functions
• Contents of window need to be refreshed
glutDisplayFunc()
• Window is resized or moved
glutReshapeFunc()
• Key action
glutKeyboardFunc()
• Mouse button action
glutMouseFunc()
• Mouse moves while a button is pressed
glutMotionFunc()
• Mouse moves regardless of mouse button state
glutPassiveMouseFunc()
• Called when nothing else is going on
glutIdleFunc()
3: Register Callback Functions
Set up any callback function you’re going to use

void main (int argc, char **argv)


{
……
glutDisplayFunc ( display ); // display callback
glutReshapeFunc ( resize ); // window resize callback
glutKeyboardFunc ( key ); // keyboard callback

……
}
Rendering Callback
It’s here that does all of your OpenGL rendering
void display( void )
{
int k;
glClear(GL_COLOR_BUFFER_BIT);
for( k=0; k<5000; k++)
……
}
Window Resize Callback
It’s called when the window is resized or moved

void resize(int w, int h)


{
……
display();
}
Keyboard Input Callback
It’s called when a key is struck on the keyboard

void key( char mkey, int x, int y )


{
switch( mkey )
{
case ‘q’ :
exit( EXIT_SUCCESS );
break;
……
}
}
4. Event Process Loop
This is where your application receives events,
and schedules when callback functions are called
void main (int argc, char **argv)
{
……
glutMainLoop();
}
2D Geometric Primitives
• Primitives – fundamental entities
such as point and polygons
• Basic types of geometric primitives
– Points
– Line segments
– Polygons

31
2D Geometric Primitives

GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP

GL_POLYGON GL_QUADS GL_TRIANGLES GL_TRIANGLE_FAN

All geometric primitives are specified by vertices


32
Geometry Commands
• glBegin(GLenum type)
marks the beginning of a vertex-data list
that describes a geometric primitives

• glEnd (void)
marks the end of a vertex-data list

• glVertex*(…)
specifies vertex for describing a geometric object
33
Specifying Geometric
Primitives
glBegin( type );
glVertex*(…);
……
glVertex*(…);
glEnd();
type determines how vertices are combined

34
Types

GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP

GL_POLYGON GL_QUADS GL_TRIANGLES GL_TRIANGLE_FAN

35
Types
GL_POINTS
GL_LINES : each successive pair for a ling segment
GL_LINE_STRIP: vertices defining a sequence of
line segments
GL_LINE_LOOP: GL_LINE_STRIP + the last vertex
connects to the first
GL_POLYGON : sequence of vertices of polygon,
filled
GL_QUADS: each successive group of four vertices
for a quadrilaterals
GL_TRIANGLES: each successive group of three
vertices for a triangle
GL_TRIANGLE_FAN: first three vertices for the
first triangle and each subsequent vertex with
the first vertex and the previous vertex for the
next triangle
36
Attribute : Line
void glLineWidth(GLfloat width)
– Set the width in pixel. Default is 1.0

void glLineStripple(GLint factor, GLushort


pattern)

37
Rectangles
• glRect*() – defines 2D filled
rectangle aligned with the axes.

void glRect{sifd} (TYPE x1, TYPE y1, TYPE x2, TYPE y2);

38
void drawSquare ()
Example
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f ( 0.0, 0.0 );
glVertex2f ( 1.0, 0.0 );
glVertex2f ( 1.1, 1.1 );
glVertex2f ( 0.0, 1.0 );
glEnd();
glFlush(); // force the renderer to output the results
}

39
OpenGL Color
• There are two color models in
OpenGL
– RGB Color (True Color)
– Indexed Color (Color map)

40
RGB Color Model

•R, G, B components are stored for each pixel

41
RGB Color

Red

Green

Blue
42
How Many Colors?
color_depth
2
Color number =
For example:
4-bit color
4 = 16 colors
2
8-bit color
28 = 256 colors
24-bit color
2 24= 16.77 million colors
43
How Much Memory?
Buffer size = width * height *color
depth
For example:
If width = 640, height = 480, color depth = 24 bits
Buffer size = (640 * 480 * 2) bytes
If width = 640, height = 480, color depth = 32 bits
Buffer size = (640 * 480 * 4) bytes

44
Alpha Component
Alpha value
A value indicating the pixels opacity
0 usually represents totally transparent and
the 1 represents completely opaque

Alpha buffer
Hold the alpha value for every pixel
Alpha values are commonly represented in 8
bits, in which case transparent to opaque
ranges from 0 to 255
45
RGB Color Commands
• glColor*(…)
specifies vertex colors

• glClearColor(r, g, b, a)
sets current color for cleaning color buffer

46
Example
void drawLine (GLfloat *color)
{
glColor3fv ( color );
glBegin(GL_LINE);
glVertex2f ( 0.0, 0.0 );
glVertex2f ( 1.0, 0.0 );
glEnd();
}

47
Example
void drawLine (GLfloat *color)
{
glBegin(GL_LINE);
glColor3f(1.0,0.0,0.0 );
glVertex2f ( 0.0, 0.0 );
glColor3f(0.0,0.0,1.0);
glVertex2f ( 1.0, 0.0 );
glEnd();
}
48
Color Interpolation
glShadeModel(GL_SMOOTH);
Or
glShadeModel(GL_FLAT); - the last
vertex color

• Linear interpolation for a line


• Bilinear interpolation for a polygons
49

You might also like