# Unit 2: Graphics Programming The OpenGL

By Shubha Raj K.B.

1

Objectives
2.1 The Sierpinski Gasket 2.2 Programming 2D Applications • Co-ordinate systems 2.3 The OpenGL API • Graphics Functions • The Graphics pipelines and state machines • The OpenGL Interface 2.4 Primitives and Attributes 2.5 Color 2.6 Viewing 2.7 Control Functions 2.8 The Gasket program 2.9 Polygons and Recursion 2.10 The 3d Gasket 2.11 Plotting Implicit Functions
2

We start with 3 points in space if they are not collinear, they are the vertices of a unique triangle 1. Pick an initial point (x,y,z) at random inside the triangle 2. Select one of the 3 vertices at random 3. Find the location halfway between the initial point and the randomly selected vertex. 4. Display this new point 5. Replace the point at (x,y,z) with this new point 6. Return to step 2
3

Display_the_point(pt). for (some_number_of_points) { pt=generate_a_point().main() { initialize_the_system(). } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 4 . } Cleanup().

2 Programming 2D Applications Use pen-plotter API.2. P=(x.y) Or P can be represented by column matrix glVertex*() *= ntv Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 5 .y.0) or p=(x.

{250.0}.0. glEnd(). int rand(). /* pick a vertex at random */ /* Compute point halfway between selected vertex and old point */ p[0] = (p[0]+vertices[j][0])/2.void display( void ) { /* define a point data type */ typedef GLfloat point2[2]. /* A triangle */ int i.0. k. p[1] = (p[1]+vertices[j][1])/2.400.0.0. k++) { j=rand()%3.50.0}}. /* An arbitrary initial point inside traingle */ /* compute and plots 5000 new points */ for( k=0. /* standard random number generator */ point2 p ={75. /* plot new point */ glBegin(GL_POINTS). point2 vertices[3]={{0.{400.0. } glFlush(). j.0}. /* clear buffers */ } 6 . k<5000. glVertex2fv(p).0}.0.

a platform-independent API that was .1 Co-ordinate Systems The success of GL lead to OpenGL (1992).Device or Window or Screen co-ordinates • GS rather than the user is responsible for mapping.2. Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 7 .2.Focus on rendering .Easy to use .Omitted windowing and input to avoid window system dependencies • Device-independent graphics .World or object co-ordinates .Close enough to the hardware to get excellent performance .

3 The OpenGL interface: gl.glu. The Graphics pipelines and state machines 2.3.1 Graphics functions 2. glut Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 8 .3.2.3.2.3 The OpenGL API 2.

WGL for Windows .GLX for X window systems .The OpenGL API • OpenGL core library .AGL for Macintosh Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 9 .Provides functionality in OpenGL core but avoids having to rewrite code • Links with window system .GL on most unix/linux systems (libGL.OpenGL32 on Windows .a) • OpenGL Utility Library (GLU) .

• Outputs are primarily the graphics sent to output devices • Example .function calls from an application program. • Graphics system is a box whose inputs are .measurements from input devices.outputs as primitives.inputs and outputs. . • This term is used to denote a system whose properties are described only by its .Simplified view of inputs as function calls and . . such as the mouse and keyboard and messages from os.Graphics System as a Black box • our basic model of a graphics package is a black box.

Graphics system as a black box • Application program function calls output • Data Graphics System Input Input/output devices .

Polygons • Attributes (HOW) • Viewing (CAMERA) • Transformations • Control (GLUT) • Input (GLUT) • Query (Device independent programs.2 color) Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 12 .2.Points .3.1 OpenGL Functions 7 different types of functions • Primitives (WHAT) .Line Segments .

glEnd(). line segments.0). polygons. glEnd(). the primitives can include . glVertex2f(100. glBegin(GL_LINES).200. .200.points. pixels.0). • Depending on the API.Primitive function • Define the low level objects or atomic entities that our system can display.0. text . • Example glBegin(GL_POINTS). and various type of curves and surfaces.0).0. glVertex2f(100. glVertex2f(300.400.0.

0.Attribute function • To perform operations ranging from choosing the color with which we display a line segment.Eg glColor3f(1.0.0). . • To picking a pattern with which to fill the inside of a polygon. . • To selecting a typesafe for the title on a graph.0.0. glLineWidth(width).

ty. sz).although APIs differ in the degree of flexibility they provide in choosing a view. sy.glViewport (xvmin. . vy. .Viewing and transformation • The viewing functions allows us to specify various views. ywmax). vpWidth. • Transformation function that allows to carry out transformations of objects. . vz). ywmin. vpHeight).glTranslatef (tx. . . translation and scaling. yvmin.glRotatef (theta. vx. tz). . such as rotation. xwmax.gluOrtho2D (xwmin.glScalef (sx.

. .Input function • Allows us to deal with the diverse forms of input that characterize modern graphics systems.glutInitWindowSize(500. int y)). Control function • Enable us to communicate with the window system.void glutKeyboardFunc(void (*func) (unsigned char key.500). int x. . to initialize our programs and to deal with any errors that take place during the execution of our programs.

.Query function • How many color are supported or • The size of the display. • Camera parameters or • values in the frame buffer.

• A black box that contains a finite state machine.The graphics pipeline and state machine • Entire graphics system is a state machine. . • This state machine has inputs that come from the application program. • These inputs may change the state of the machine or can cause the machine to produce a visible output.

2.Primitive generating • Can cause output if primitive is visible • How vertices are processed and appearance of primitive are controlled by the state .3.2 The Graphics Pipeline and State Machines • OpenGL is a state machine • OpenGL functions are of two types .State changing • Transformation functions • Attribute functions Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 19 .

From the Pesspective of API. Those that either changes the state inside the machine or return state information. Those that define primitives that flow through a pipeline inside the state machine • glVertex. Two types of graphics functions: 1. once we set a color. • For example. that color remains the current color until it is changed through a color-altering function .first type 2. • Their values remain unchanged until we explicitly change them through functions that alter the state. • In openGL most parameters are persistent.

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 Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 21 .

GLU(OpenGL Utility libarary) .GLUT(openGL Utility Toolkit) GL functions in the GL library have names that begin with the letters gl and are stored in a library usually referred to as GL .GL library .3 OpenGL interface • Three libraries .2.3.

• GLU .This library uses only GL functions but contains code for creating common objects and simplifying viewing. we need at least one more library. .Functions in the GLU library begin with the letter glu. GLUT To interface with the window system and to get input from external devices into our programs. .

For the X window system. • AGL . this library is called GLX WGL for windows. .for the macintosh it is agl or(Apple graphics library). • Rather than using a different library for each system.• GLX : OpenGL Extension for the X Window System” . • GLUT provides minimum functionality that should be expected in any modern windowing system. it is wgl .we use a readily available library called the openGL utility Toolkit(GLUT).WGL or Wiggle is the windowing system interface to the Microsoft Windows implementation of the OpenGL specification .

glu.h> • Is sufficient to read in glut.gl.h> • or • #include<GLUT/glut.h.h .h. • GL_FILL and GL_POINTS are defined in the header file(.h) • #include<GL/glut.• Glut uses GLX and the X libraries.

Library organization for an xwindows system environment Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 26 .

h. Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 27 . glu.h and glut.….h . GLdouble.Examples -glBegin(GL_POLYGON) -glClear(GL_COLOR_BUFFER_BIT) • include files also define OpenGL data types: GLfloat.Note #include <GL/glut.h> should automatically include the others .OpenGL #defines • Most constants are defined in the include files gl.

4 PRIMITIVES AND ATTRIBUTES .2.

Image (or) raster primitives Geometric primitives • Include points. line segments. • These primitives pass through a geometric pipeline.• OpenGL supports two classes of primitives: . curves and surfaces. polygons. • where they are subject to a series of geometric operations that determine • whether a primitive is visible or not • Where on the display it appears if it is visible.Geometric primitives . .

Primitives and Attributes • Minimal set • Other set • OpenGL supports 2 classes of primitives .Image or Raster primitives Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 30 .Geometric primitives .

OpenGL Primitives GL_POINTS GL_LINES GL_LINE_STRIP GL_POLYGON GL_LINE_LOOP GL_TRIANGLES GL_QUAD_STRIP GL_TRIANGLE_STRIP GL_TRIANGLE_FAN Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 31 .

2.4.1. Polygon basics
• Line segments and polylines • Methods of displaying a polygon • Simple polygon/Nonsimple • Convex/NonConvexity

32

2.4.2 Polygon types in OpenGL
Polygons, Triangles and quadrilaterals, strips and fans • GL_POLYGON • GL_TRIANGLES • GL_QUADS • GL_TRIANGLE_STRIP • GL_QUAD_STRIP • GL_TRIANGLE_FAN
33

• Geometric Primitives can be used as building blocks for other geometric objects. • Raster primitives such as arrays of pixels pass through a separate parallel pipeline. • The basic OpenGL geometric primitives are specified by sets of vertices.
glBegin(type);
glVertex*(…); . . glVertex*(…); glEnd();

Simplified OpenGL Pipeline Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 35 .

.Whether or not they have interiors.• The value of type specifies how OpenGL assembles the vertices to define geometric objects. All the basic types are defined by sets of vertices. • Other code and OpenGL function calls can occur between glBegin and glEnd. • Major difference between the geometric types .

LINE SEGMENTS • Finite sections of lines between two vertices called line segments. . • you can use a sequence of line segments to connect data values for a graph. • You can also use line segments for the edges of closed objects. such as polygon that have interiors. USES • Use line segments to define approximations to curves.

GL_LINE_LOOP): GL_LINE_STRIP . we can use the line strip or polyline form. thus creating a closed path.Each vertex is displayed at a size of at least one pixel.If successive vertices are to be connected. . GL_LINE_LOOP . • Polylines(GL_LINE_STRIP.Successive pairs of vertices to be interpreted as the endpoints of individual segments.The primitive and their type specification include the following: • Points(GL_POINTS): . • Line segments(GL_LINES): .will draw a line segment from the final vertex to the first.

.

It can be described by line loop. . • Polygons play a special role in CG. • The performance of graphics systems is characterized by the .number of polygons per second that can be rendered. .Polygon Basics • Polygon –has a border and has a well defined interior.

• we can render or not render the edges .Polygon rendering • Render only its edges. • Render its interior with a solid color or a pattern.

Filled objects .

Methods of displaying a polygon .

• Three properties will ensure that a polygon will be displayed correctly.as long as no two edges of a polygon cross each other. • It must be simple.we have a simple polygon. Well defined interiors. Simple  in 2D . .convex and flat.

• p1 and p2 are arbitrary points inside a polygon and the entire line segment connecting them is inside the polygon. tetrahedra. • Convex objects include triangle. spheres.Convex • An object is convex if all points on the line segment between any two points inside the object or on its boundary are inside the object. circles. parallepipeds. rectangles. .

• Simple: edges cannot cross • Convex: All points on line segment between two points in a polygon are also in the polygon • Flat: all vertices are in the same plane .

Convex: All points on line segment between two points in a polygon are also in the polygon .OpenGL will produce output if these conditions are violated but it may not be what is desired • Triangles satisfy all conditions nonconvex polygon 47 nonsimple polygon Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 .Flat: all vertices are in the same plane • User program can check if above true .Polygon Issues • OpenGL will only display polygons correctly that are .Simple: edges cannot cross .

• a) Simple polygon • B) Nonsimple polygon .

• Convexity .

Convex objects .

successive vertices define line segments and a line segment connects the final vertex to the first. . . • Triangle and quadrilaterals (GL_TRIANGLES. .use the function glPolygonMode to tell the renderer to generate only the edges or just points for the vertices. instead of fill.GL_QUADS): .Polygon types in OpenGL • Polygons(GL_POLYGON): .Successive groups of three and four vertices are interpreted as triangles and quadrilaterals. GL_LINE).glPolygonMode(GL_FRONT_AND_BACK.

GL_TRIANGLE_FAN) .• Strips and Fans(GL_TRIANGLE_STRIP.Combine two new vertices with the previous two vertices to define a new quadrilateral. and subsequent triangles are formed from one new point. GL_QUAD_STRIP. Quadstrip . the previous point and the first point. Triangle strip .Triangle fan is based on the one fixed point. . The next two points determine the first triangle.Each additional vertex is combined with the previous two vertices to define a new triangle.groups of triangles or quadrilaterals that share vertices and edges. Triangle fan .

Polygon types .

.

.2.3 Approximating a sphere • Fans and strips allow us to approximate many curved surfaces. • Ex: For sphere use a set of polygons defined by lines of longitude and latitude.4.

Stroke . .It can be manipulated by our standard transformations.Raster Stroke text • is constructed as are other geometric objects • Advantage .It can be defined to have all the detail of any other object.4 TEXT • There are two forms of text: .Using transformation we can make a stroke character bigger or rotate . .4.2.

Stroke text • Defining a full 128 or 256 character stroke font can be complex. • standard postscript fonts . • It takes significant memory and processing time.

. • Each block defines a single character by the pattern of 0 and 1 bits in the block.which moves the block of bits using a single call.A raster character can be placed in the frame buffer rapidly by a bit-block-transfer(bitblt) operation.Raster text • simple and fast. • Bit-block-transfer . • Characters are defined as rectangles of bit called bit blocks.

• a)Raster text b) Raster character replication .

• GLUT library provides a few predefined bitmap and stroke character sets .Where c is the number of the ASCII character that we wish to be placed on the display . c) . • glutBitmapCharacter(GLUT_BITMAP_8_BY_13.Replicating • you can increase the size of raster characters by replicating or duplicating pixels. a process that gives larger characters a blocky appearance.

5 Curved objects • Two approaches .We can use the primitives that we have to approximate curves and surfaces.2. parametric polynomial curves and surfaces .mathematical definitions of curved objects • supported by GLU library • quadric surfaces.4. • a circle with a regular polygon with n sides .

2.which can occur either at the • rendering stage or • within the user programs 2.4.5 Curved objects 1.Tessellation .We approximate a curves surfaces by a mesh of convex polygons. Use the primitives that we have to approximate curves and surfaces • Ex: Circle .Sphere (Triangles and Quadrilaterals) • Tessellation . Start with the mathematical definitions of curved objects Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 62 .

6 Attributes • Color • Thinkness of a line • Pattern used to fill a polygon Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 63 .2.4.

.point (color.  no memory  once erased from the display. polygon (pattern types.it is lost. type). width. line (color. italic. size). font.Attributes An Attributes is any property that determines how a geometric primitive is to be rendered . display list keep objects in memory so that these objects can be redisplayed.text (height. etc).thickness. . underlined)) immediate mode  primitives are not stored in the display system but rather passed through the system for possible rendering as soon as they are defined. style (bold.

Size and width (points.Stipple pattern (lines. polygons) .Attributes • Attributes are part of the OpenGL state and determine the appearance of objects . lines) . polygons) . lines.Color (points.Polygon mode • Display as filled: solid color or stipple pattern • Display edges • Display vertices 65 Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 .

Our Brain receive three values.2. • Tristimulus values .5 COLOR • A visible color can be characterized by a function C(l) that occupies wavelengths from about 350 to 780nm. . Color theory If two colors produce the same tristimulus values.then they are visually indistinguishable.

• Additive color model .green. magenta.Primary colors add together to give the perceived color. projectors • Subractive color model Primaries are complementary colors: Cyan. .The primaries are red.Example of additive color include • CRT. yellow(CMY) Example: commercial printing and painting .blue(RGB) .

Color formation • Additive color Subtractive color .

Color solid .

• All colors along this line have shades of gray. • Principal diagonal of the cube connects the origin(black) with white.Color solid • Draw Solid using a coordinate system corresponding to the three primaries. .

2.1 RGB Color .5.

green and blue.red. 1 byte for each red. • There are 224 possible colors-referred to as 16M colors. . • Each pixel consist of 24 bits(3 bytes).green. • Each pixel has separate red. and blue images. green and blue components that correspond to locations in memory.• There are separate buffers for .

• Color components between 0.0 .0. A=0.0 and 1.glColor3f(1.0. .0. RGBA SYSTEM A-alpha The alpha value will be treated by OpenGL as either an opacity or transparency.Fully opaque .0 .0 denotes the maximun(saturated value).0.0). where 1.0.Fully transparent A=1.

1. • glClearColor(1.0).1.0. .• Must clear the window whenever we want to draw a new frame. defines an RGB color clearing color that is white.0.1.0.

• Analogy with an artist who paints in oil. • Images are called indexed color because the actual image color data for each pixel is the index into this palette . . • Smaller group of pixel-assign to R. • Each pixel was 8 bits deep.5.B.G.2. • It gives less no of color.limited in depth.2 Indexed Color • Early graphics systems had frame buffers that were . • Indexed color provide solution that allowed applications to display a wide range of color.

• fig:color lookup table .• 256 entries in the table constitute the user’s color palette.

Fig:Indexed color .

Each pixel value or index is an integer between 0 and • We can produce any of 23m colors on the display. • We can display colors with precision of m bits. • The user program fills the 2k entries of the table with the desired colors . . the second RGB color is index 1. . etc.green and blue.There can be at most only 256 colors in the palette.using m bits for each of red . Suppose that our frame has k bits per pixel. • We handle the specification through a user defined color lookup table that is of size 2k *3m.2m greens and 2m blues.• • 2k-1.but the frame buffer can specify only 2k of them. . • The first RGB color in the table is index 0. . .we can choose from 2m reds.

entries in a color table for each window through the following function: glutSetColor(int color.GLfloat red.GLfloat green. . • GLUT allows us to set the . That selects a particular color out of the table.the present color is selected by a function such as glIndexi(element).GLfloat blue) .• If we are in color index mode.

• When early computer screens were commonly limited to 256 colors.bandwidth and . • 8-bit indexed images are still widely used to save .• Advantage . .Fewer other hardware components.indexed color methods were essential.storage space.Less memory . .

• set point size – let us use 2 pixels size glPointSize(2. • rendering color for points – set to RED glColor3f(1.0. 1.0). 1. . 1.0.0.3 Setting of color attributes • clear color glClearColor(1.0.0.2.5. 0.0). • These attributes will be valid for all the time if not changed explicitly.0). 0.

6 VIEWING .2.

by carrying out a sequence of operations in its pipeline. • The application program specifies . .• Camera forms an image by exposing a film.parameters for object and the camera. • The computer system forms an image .

• Image plane is fixed. move camera far from this plane. .6.1 Orthographic view • Place the camera infinitely far from objects. • All projectors become parallel and .2.the center of projection is replaced by direction of projection.

• Projectors that are parallel to the positive . . • Projectors are perpendicular or orthogonal to the projection plane.z-axis and the projection plane at z=0. • Slide the projection plane along the z-axis without changing where the projectors intersect the plane.

Orthographic Projection Projectors are orthogonal to projection surface .

• There is reference point in the projection plane from which we can make measurements of a view volume and a direction of projection. . . • Reference point -origin.special orthographic camera resides in the projection plane. camera points in the negative z-direction.• For orthographic viewing.

The default camera and an orthographic view volume .

Viewing volume .

Gldouble near.0).• It takes a point(x.y. GLdouble bottom. . • All parameters are distances measured from the camera.z) and projects it into the point(x. an orthographic projection with a right parallelepiped viewing volume is specified via the following void glOrtho(GLdouble left.GLdouble far). GLdouble right.y.GLdouble top. • In openGL.

2 x 2 x 2 cube. with the origin in the center. .0). • In 2D plane.0. • If we do not specify a viewing volume.at (-1.-1. .openGL uses its default.0) and upper corner is at(1.1.0.• The orthographic projection “sees” only those objects in the volume specified by viewing volume. the bottom-left corner is .

0 respectively.objects outside are clipped out. GLdouble top) • Near and far set to -1. .6. • Objects inside the rectangle are in the image. • Take a rectangular area of our two dimensional world and transferring its contents to the display.2.0 and 1. GLdouble bottom. • The area of the world that we image is known as viewing rectangle or clipping rectangle. Gldouble right. .2 2D viewing • void gluOrtho2D (GLdouble left.

• b) objects after clipping .2D viewing • a) objects before clipping.

the view or clipping volume becomes a clipping window Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 95 .bottom.top) • In two dimensions.and threedimensional viewing • In glOrtho(left. far) the near and far distances are measured from the camera • Two-dimensional vertex commands place all vertices in the plane z=0 • If the application is in two dimensions. right. top. we can use the function gluOrtho2D(left. right. near. bottom.Two.

Matrics • Two things to specify: .Physical location of camera in the scene (MODELVIEW matrix in OpenGL).Projection properties of the camera (PROJECTION matrix in OpenGL): Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 96 . .

glMatrixMode (GL_MODELVIEW) Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 97 . 1.0).so we start with an identity matrix and alter it with a projection matrix that gives the view volume glMatrixMode (GL_PROJECTION) glLoadIdentity().2. • Transformation functions are incremental .3 Matrix Modes • In OpenGL. 1.0.0. projection is carried out by a projection matrix (transformation) • There is only one set of transformation functions so we must set the matrix mode first glMatrixMode (GL_PROJECTION). glOrtho(-1. -1.0.0.0.6. -1. 1.

GLdouble right. .GLdouble top. GLdouble far). GLdouble near. GLdouble bottom.Perspective projection void glFrustum(GLdouble left.

GLdouble far). GLdouble bottom. GLdouble near. .Orthographic projection void glOrtho(GLdouble left. GLdouble top. GLdouble right.

2.7 CONTROL FUNCTION

2.71. Interaction with the window system
• GLUT is a library of function that provides a simple interface between systems.
- Window or screen window denote a rectangular area of our display.

• Window
- has height and width - it displays the contents of the frame buffer. - Positions in the window measured in terms pixels.

• The window in which the graphics system
- output appears is one of the windows managed by the window system.

• In science and engg- Lower left corner is the origin.

• All raster system- Top left corner is origin.

• OpenGL- Bottom left corner is origin.

• Screen resolution-1280 x1024 • Frame buffer must have resolution equal to screen size.

2.7.2 Aspect ratio and viewports
• The aspect ratio of a rectangle is the
- ratio of the rectangle’s width to its height.

• If different in glOrtho and glutInitWindowSize - undesirable side effects

• If they differ, objects are distorted on the screen. • To avoid this distortion if we ensure that
- the clipping rectangle and display window have the same aspect ratio.

Aspect ratio mismatch
• • • • a) viewing rectangle b)display window

y.w.h) • Values in pixels (screen coordinates) Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 105 .Viewports • Do not have use the entire window for the image: glViewport(x.

Where the Title at the top of the window is given by string title. • Specifies a 480 x 640 window in the top-left corner of the display. • Open OpenGL window using GLUT function glutCreateWindow(char *title) . • Use following GLUT functions before window creation to specify these parameters. • glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE).480).• Interaction between windowing system and OpenGL is initialized by the following function. .char **argv) Argument is same as main.0). • glutInitWindowPosition(0. glutInit(int *argc. • glutInitWindowSize(640.

A Simple Program Generate a square on a solid background Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 107 .

5. -0. } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 108 . glVertex2f(0. glEnd(). char** argv){ glutCreateWindow("simple").5. glVertex2f(-0. glVertex2f(-0.simple. glFlush().5).5).5. -0. 0.5.h> void mydisplay(){ glClear(GL_COLOR_BUFFER_BIT). glBegin(GL_POLYGON). } int main(int argc. 0.5).5). glutMainLoop(). glVertex2f(0.c #include <GL/glut. glutDisplayFunc(mydisplay).

Event Loop • Note that the program defines a display callback function named mydisplay . • for example when the window is opened .The display callback is executed whenever OpenGL decides the display must be refreshed.Every glut program must have a display callback .The main function ends with the program entering an event loop Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 109 .

c #include <GL/glut.h int main(int argc.h> includes gl.argv). init().500). define window properties glutDisplayFunc(mydisplay). char** argv) { glutInit(&argc.main. } display callback set OpenGL state enter event loop 110 Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 .0). glutInitWindowPosition(0. glutMainLoop(). glutCreateWindow("simple"). glutInitWindowSize(500. glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB).

1. 1. 0.init.0).0). glLoadIdentity (). 1. glColor3f(1.0.0. 1.0. 1. 1.0).0. } viewing volume Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 111 .0.0. 0.0.0.0.0. glOrtho(-1. -1. fill/draw with white glMatrixMode (GL_PROJECTION). -1.c black clear color opaque window void init() { glClearColor (0.

7.callbacks • Display function • Input and window functions 112 Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 .4 Program Structure • Most OpenGL programs have a similar structure that consists of the following functions -main(): • defines the callback functions • opens one or more windows with the required properties • enters event loop (last executable statement) -init(): sets the state variables • Viewing • Attributes .2.

simple.but we have defined all the relevant state values through function calls • using the default values • In particular. we shall see the same output .Window properties Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 113 .Colors .Viewing conditions . we set .c revisited • In this version.

RGB color .Single buffering .GLUT functions •glutInit allows application to get command line arguments and initializes system •gluInitDisplayMode requests properties for the window (the rendering context) .Properties logically ORed together •glutWindowSize in pixels •glutWindowPosition from top-left corner of display •glutCreateWindow create window with title “simple” •glutDisplayFunc display callback •glutMainLoop enter infinite event loop Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 114 .

it is the size of the viewing volume that determines what will appear in the image • Internally.object or problem coordinates • The viewing specifications are also in object coordinates and . OpenGL will convert to camera (eye) coordinates and later to screen coordinates • OpenGL also uses some internal representations that usually are not visible to the application Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 115 .Coordinate Systems • The units in glVertex are determined by the application and are called .

1. /* white background */ glColor3f(0.0). /* draw in red */ /* set up viewing */ /* 500 x 500 window with origin lower left */ glMatrixMode(GL_PROJECTION). 1. 500.8 THA GASKET PROGRAM void myinit(void) { /* attributes */ glClearColor(1.0.0. glLoadIdentity().0.0.0. 0. glMatrixMode(GL_MODELVIEW).0).2.0. 1.0. 1.0. } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 116 . gluOrtho2D(0. 500. 0.0).

0. p[1] = (p[1]+vertices[j][1])/2.{400.void display( void ) { /* define a point data type */ typedef GLfloat point2[2].0.0.{250.0. k. /* plot new point */ glBegin(GL_POINTS). k++) { j=rand()%3. int rand().0}.0}}. /* An arbitrary initial point inside traingle */ glClear(GL_COLOR_BUFFER_BIT). k<1000. /*clear the window */ /* compute and plots 5000 new points */ for( k=0. /* A triangle */ int i. /* pick a vertex at random */ /* Compute point halfway between selected vertex and old point */ p[0] = (p[0]+vertices[j][0])/2.0}. j.50. glVertex2fv(p). /* standard random number generator */ point2 p ={75.0. point2 vertices[3]={{0. glEnd().400. /* clear buffers */ } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 117 . } glFlush().0}.0.

2.9 Polygon and Recursion Sierpinski Gasket (2D) • Start with a triangle • Connect bisectors of sides and remove central triangle • Repeat Fig: Bisecting the sides of a triangle Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 118 .

Example • subdivisions Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 119 .

The gasket as a fractal • Consider the filled area (black) and the perimeter (the length of all the lines around the filled triangles) • As we continue subdividing .It is neither two.but the perimeter goes to infinity • This is not an ordinary geometric object .nor three-dimensional • It is a fractal (fractional dimension) object Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 120 .the area goes to zero .

-0.58}.0.Gasket Program #include <GL/glut. {0.h> /* initial triangle */ GLfloat v[3][2]={{-1.15}}. 1. /* number of recursive steps */ Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 121 . {1.0.58}.0. int n. -0.

GLfloat *b. GLfloat *c) /* display one triangle { glVertex2fv(a). glVertex2fv(b). glVertex2fv(c).Draw one triangle void triangle( GLfloat *a. } */ Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 122 .

m-1). v1.b. v2. v2. GLfloat *b. m-1). } else(triangle(a.Triangle Subdivision void divide_triangle(GLfloat *a. divide_triangle(a. GLfloat *c. int m) { /* triangle subdivision using vertex numbers */ point2 v0.c)). for(j=0. v2. divide_triangle(c. /* draw triangle at end of recursion */ } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 123 . divide_triangle(b. v0. j<2. if(m>0) { for(j=0. v1. j<2. j<2. j++) v1[j]=(a[j]+c[j])/2. int j. j++) v2[j]=(b[j]+c[j])/2. j++) v0[j]=(a[j]+b[j])/2. for(j=0. m-1). v1. v0.

0.0.0. -2.display and init Functions void display() { glClear(GL_COLOR_BUFFER_BIT). v[1]. 1. glMatrixMode(GL_MODELVIEW).0.0. n).0. gluOrtho2D(-2. glFlush(). } void myinit() { glMatrixMode(GL_PROJECTION).0). 2. divide_triangle(v[0].0). glBegin(GL_TRIANGLES).1. glLoadIdentity().0) glColor3f(0. } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 124 .0.0. glClearColor (1.0. glEnd(). 2. 1.0. v[2].

500). glutInit(&argc. } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 125 . myinit(). glutDisplayFunc(display). glutCreateWindow(“2D Gasket"). glutInitWindowSize(500. glutMainLoop(). glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB). argv).main Function int main(int argc. char **argv) { n=4.

.rather than in the function triangle and using GL_TRIANGLES rather than GL_POLYGON in glBegin.we call glBegin and glEnd only once for the entire gasket rather than once for each triangle Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 126 .Efficiency Note • By having the glBegin and glEnd in the display callback .

Sierpinski gasket: a fractal • Introduce hidden-surface removal Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 127 .Objectives • Develop a more sophisticated threedimensional example .

two-dimensional applications .Have to worry about the order in which polygons are drawn or use hidden-surface removal . flat Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 128 .Polygons should be simple. convex.Not much changes .2.Use glVertex3*( ) .10 Three-dimensional Applications • In OpenGL.are a special case of three-dimensional graphics • Going to 3D .

OpenGL function format function name glVertex3f(x.y.y.z are floats dimensions belongs to GL library glVertex3fv(p) p is a pointer to an array Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 129 .z) x.

we can start with a tetrahedron Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 130 .2.10.1 Use of 3D points • We can easily make the program threedimensional by using GLfloat v[3][3] glVertex3f glOrtho • But that would not be very interesting • Instead.

10.2. Use of Polygons in 3D • We can subdivide each of the four faces • Appears as if we remove a solid tetrahedron from the center leaving four smaller tetrahedra Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 131 .2.

GLfloat *c) { glVertex3fv(a). } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 132 .triangle code void triangle( GLfloat *a. glVertex3fv(c). GLfloat *b. glVertex3fv(b).

v3. GLfloat *c. v2[3]. v2. v1. v3. v3[3]. j<3. v1. divide_triangle(c. divide_triangle(b. j++) v3[j]=(b[j]+c[j])/2. divide_triangle(a. int m) { GLfloat v1[3].b. int j. for(j=0. j<3. j++) v1[j]=(a[j]+b[j])/2.c)). m-1). j++) v2[j]=(a[j]+c[j])/2. GLfloat *b. v2. j<3.subdivision code void divide_triangle(GLfloat *a. m-1). m-1). } else(triangle(a. for(j=0. if(m>0) { for(j=0. } Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 133 .

v[1]. Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 134 . m).1. v[1]. glColor3f(0.0.0.0).0.0.0. } v[2].1. divide_triangle(v[0]. v[2].0. divide_triangle(v[3].0. m). divide_triangle(v[0]. glColor3f(0.0.0. glColor3f(0. v[3].0. v[1]. m). m). divide_triangle(v[0]. v[3].0.0).0). v[2].0.tetrahedron code void tetrahedron( int m) { glColor3f(1.0.0).0.

.the front triangles are not always rendered in front of triangles behind them get this want this Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 135 .Almost Correct • Because the triangles are drawn in the order they are defined in the program.

saves depth information as objects are rendered so that only the front objects appear in the image Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 136 .3 Hidden-Surface Removal • We want to see only those surfaces in front of other surfaces • OpenGL uses a hidden-surface method called the z-buffer algorithm that .10.2.

. the z-buffer.to store depth information as geometry travels down the pipeline • It must be .Using the z-buffer algorithm • The algorithm uses an extra buffer.Requested in main • glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH) .Cleared in the display callback • glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 137 .Enabled in init or in main • glEnable(GL_DEPTH_TEST) .

we divided the surface of each face • We could also divide the volume . .using the same midpoints • The midpoints define four smaller tetrahedrons.Surface vs Volume Subdvision • In our example.one for each vertex • Keeping only these tetrahedrons removes a volume in the middle • See text for code Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 138 . .

Volume Subdivision Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 139 .

Colors and other attributes are not part of the object but are assigned when the object is rendered • We can create conceptual vertex colors by code such as glColor glVertex glColor glVertex Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 140 .Color and State • The color as set by glColor becomes part of the state and will be used until changed .

OpenGL interpolates vertex colors across visible polygons • Alternative is flat shading .Smooth Color • Default is smooth shading .Color of first vertex determines fill color •glShadeModel (GL_SMOOTH) or GL_FLAT Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 141 .

MATRIX MODE • Using glMatrixMode function you chose which matrix you want to change.By default.this one is used to convert 3D coordinate to 2D coordinate for final pixel position.this one is used to move vertex to model space. . • A computer monitor is a 2D surface. • GL_PROJECTION: . . We need to transform 3D scene into 2D image in order to display it. which assumes everything you draw will be in one 3Dspace. GL_PROJECTION matrix is for this projection transformation • GL_TEXTURE: this one is used to alter texture coordinates. • OpenGL works with 3 matrices: GL_MODELVIEW: . the matrix mode is GL_MODELVIEW.

. . . a variable that is set to one type of matrix that is also part of the state.multiplying together or Concatenating a number of transformation matrices to achieve the desired image of a primitive • Two important matrices: .Model-view .Select the matrix to which the operations apply by first setting the matrix mode.Matrix mode • Pipeline graphics system depends on .Which are initially set to identity matrix.Projection matrix .The usual sequence is to modify the initial identity matrix by applying sequence of transformations.

100 ). . 0. 0 ). • GL_PROJECTION_MATRIX = IDENTITY * ORTHOGRAPHIC_MATRIX * TRANSLATION_MATRIX * ROTATION_MATRIX.0. • glMatrixMode(GL_PROJECTION). glOrtho(-1. -1. -1. each subsequent operation is applied to that particular matrix mode and below it .Concept behind this code??Unit4 and 5 • Once you set the matrix mode. 1. 100.0). glRotate( 45. 1. 1. 1. glTranslate( 100. glLoadIdentity().

2. y) pairs connected by line segments.Solve the problem for sampled data by a technique called marching Squares Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 145 .How to display data defined by an Implicit function of the form g(x.Where the function g is known analytically such as • Equation for a unit circle centered at the origin • g(x. y)=0 . y)= x2-y2-1=0 .Display of Explicit functions of the form • Y=h(x) is straightforward because we can evaluate y for a set of values of x and then write a simple program to display these (x.11 Plotting Implicit Functions • The problem we are discussing here is . • Marching Squares .

From GL. discuss about scene Graphs.Do not have the portability . Synthetic Camera Model with a Pipeline architecture .GL was designed specifically for high-speed real-time rendering.2D. • OpenGL (Scientific and engineering applications are written in openGL) • DirectX?? .Which provide a much higher-level. Pen-Plotter Model . .(Windows).Summary of UNIT2 • GKS .Focus on Modeling in UNIT2 146 Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 . OO interface to Graphics Hardware . Device-dependent features-from graphics Cards .Many Java programmer use the JOGL bindings • In chapter 10.GAME world • Modeling-rendering Paradigm .3D. Synthetic-Camera Model • OpenGL (Silicon Graphics Inc) .GKS-3D • PHIGS and PHIGS+ . • Recently Sun Microsystems recently released their Java bindings for openGL .Most scene graph APIs are built on top of openGL.