Graphics Programming Chapter 2. CS 480/680 2Chapter 2 -- Graphics Programming Introduction:...

75
Graphics Graphics Programming Programming Chapter 2 Chapter 2

Transcript of Graphics Programming Chapter 2. CS 480/680 2Chapter 2 -- Graphics Programming Introduction:...

Graphics Graphics ProgrammingProgramming

Chapter 2Chapter 2

CS 480/680 2Chapter 2 -- Graphics Programming

Introduction:Introduction: Our approach is programming Our approach is programming

oriented. oriented. Therefore, we are going to introduce Therefore, we are going to introduce

you to a simple but informative you to a simple but informative problem: the Sierpinski Gasketproblem: the Sierpinski Gasket

The functionality introduced in this The functionality introduced in this chapter is sufficient to allow you to chapter is sufficient to allow you to write sophisticated two-dimensional write sophisticated two-dimensional programs that do not require user programs that do not require user interaction.interaction.

CS 480/680 3Chapter 2 -- Graphics Programming

1. The Sierpinski Gasket1. The Sierpinski Gasket

This problem has a long history and is This problem has a long history and is of interest in areas such as fractal of interest in areas such as fractal geometry.geometry. It can be defined recursively and randomly; It can be defined recursively and randomly;

in the limit, however, it has properties that in the limit, however, it has properties that are not at all random.are not at all random.

Assume that we start with 3 points on Assume that we start with 3 points on the plane (a triangle)the plane (a triangle)

CS 480/680 4Chapter 2 -- Graphics Programming

The construction The construction proceeds as follows: proceeds as follows:

1. Pick an initial point at 1. Pick an initial point at random inside the trianglerandom inside the triangle

2. Select one of the three 2. Select one of the three vertices at randomvertices at random

3. Find the point halfway 3. Find the point halfway between the point and the between the point and the vertexvertex

4. Mark/Draw that half-4. Mark/Draw that half-way pointway point

5. Replace the initial point 5. Replace the initial point with this new pointwith this new point

6. Go to step 26. Go to step 2

CS 480/680 5Chapter 2 -- Graphics Programming

So, what would our code look like?So, what would our code look like? initialize()initialize() for(some_number_of_points)for(some_number_of_points) {{ pt=generate_a_point();pt=generate_a_point(); display_the_point(pt);display_the_point(pt); }} cleanup();cleanup();

Although our OpenGL code might Although our OpenGL code might look slightly different, it will almost look slightly different, it will almost be this simple.be this simple.

So, let’s look at generating and So, let’s look at generating and displaying points.displaying points.

CS 480/680 6Chapter 2 -- Graphics Programming

1.1 The Pen-Plotter Model1.1 The Pen-Plotter Model Historically, most early graphics Historically, most early graphics

systems were two-dimensional systems were two-dimensional systems. The conceptual model that systems. The conceptual model that they used is now referred to as the they used is now referred to as the pen-plotter model.pen-plotter model.

Various API’s - LOGO, GKS, and Various API’s - LOGO, GKS, and PostScript -- all have their origins in PostScript -- all have their origins in this model.this model.

CS 480/680 7Chapter 2 -- Graphics Programming

The user works on a two-dimensional The user works on a two-dimensional surface of some sizesurface of some size

The following code could generate the first The following code could generate the first figure:figure:

moveto(0,0); moveto(0,0); lineto(1,0);lineto(1,0); lineto(1,1);lineto(1,1); lineto(0,1);lineto(0,1); lineto(0,0)lineto(0,0)

For certain applications, such as page For certain applications, such as page layout in the printing industry, systems layout in the printing industry, systems built on this model work well.built on this model work well.

We are more interested, however, in We are more interested, however, in the three-dimensional world.the three-dimensional world.

CS 480/680 8Chapter 2 -- Graphics Programming

As we saw in Chapter 1 we could do As we saw in Chapter 1 we could do projections of the 3D points onto the projections of the 3D points onto the 2D plane and plot with a pen.2D plane and plot with a pen.

We prefer, however, to use an API We prefer, however, to use an API that allows users to work directly in that allows users to work directly in the domain of their problem, and the domain of their problem, and have the computer carry out this have the computer carry out this projection process automatically.projection process automatically.

For two-dimensional applications, For two-dimensional applications, such as the Sierpinski gasket, we can such as the Sierpinski gasket, we can start with a three-dimensional world, start with a three-dimensional world, and regard two-dimensional systems and regard two-dimensional systems as special cases.as special cases.

CS 480/680 9Chapter 2 -- Graphics Programming

OpenGL has multiple forms for many OpenGL has multiple forms for many functions. functions.

The variety of forms allows the user to The variety of forms allows the user to select the one best suited for their problem.select the one best suited for their problem.

For a vertex function, we can write the For a vertex function, we can write the general form general form

glVertex*glVertex* where * can be interpreted as two or three where * can be interpreted as two or three

characters of the form nt or ntvcharacters of the form nt or ntv n signifies the number of dimensions (2, 3, or n signifies the number of dimensions (2, 3, or

4)4) t denotes the data type (I for integer, f for t denotes the data type (I for integer, f for

float, d for double)float, d for double) and v if present, indicates the variables are and v if present, indicates the variables are

specified through a pointer to an array rather specified through a pointer to an array rather than through the argument list.than through the argument list.

CS 480/680 10Chapter 2 -- Graphics Programming

In OpenGL, we often use basic In OpenGL, we often use basic OpenGL types, such asOpenGL types, such as Glfloat and Glint Glfloat and Glint rather than C types float and intrather than C types float and int

So, in our application, the following So, in our application, the following are appropriateare appropriate glVertex2i(Glint xi, Glint yi)glVertex2i(Glint xi, Glint yi) GLVertex3f(Glfloat x, Glfloat y, Glfloat z)GLVertex3f(Glfloat x, Glfloat y, Glfloat z)

And if we use an array to store the And if we use an array to store the informationinformation Glfloat vertex[3];Glfloat vertex[3]; glVertex3fv(vertex);glVertex3fv(vertex);

CS 480/680 11Chapter 2 -- Graphics Programming

Vertices can define a variety of Vertices can define a variety of geometric objectsgeometric objects A line segment can be defined as follows:A line segment can be defined as follows:

glBegin(GL_LINES)glBegin(GL_LINES) glVertex2f(x1,y1);glVertex2f(x1,y1); glVertex2f(x2,y2);glVertex2f(x2,y2); glEnd();glEnd();

A pair of points could be defined by:A pair of points could be defined by: glBegin(GL_POINTS)glBegin(GL_POINTS) glVertex2f(x1,y1);glVertex2f(x1,y1); glVertex2f(x2,y2);glVertex2f(x2,y2); glEnd();glEnd();

Now on to the gasket.Now on to the gasket.

CS 480/680 12Chapter 2 -- Graphics Programming

void display(void)void display(void) {{ point2 vertices[3] = {{0.0,0.0}, {250.0,500}, {500.0, point2 vertices[3] = {{0.0,0.0}, {250.0,500}, {500.0,

0.0}};0.0}}; static point2 p={75.0, 50.0};static point2 p={75.0, 50.0}; int j,k;int j,k; for(k=0; k<5000;k++)for(k=0; k<5000;k++) {{ j=rand( )%3;j=rand( )%3; p[0]=(p[0]+triangle[j][0])/2;p[0]=(p[0]+triangle[j][0])/2; p[1]=(p[1]+triangle[j][1])/2;p[1]=(p[1]+triangle[j][1])/2; glBegin(GLPOINTS);glBegin(GLPOINTS); glVertex2fv(p);glVertex2fv(p); glEnd();glEnd(); }} glFlush();glFlush(); }}

CS 480/680 13Chapter 2 -- Graphics Programming

CS 480/680 14Chapter 2 -- Graphics Programming

We have now written the core of the We have now written the core of the program. But we still have to worry program. But we still have to worry about issues such as:about issues such as: 1. In what color are we drawing?1. In what color are we drawing? 2. Where on the screen does our image 2. Where on the screen does our image

appear?appear? 3. How large will the image be?3. How large will the image be? 4. How do we create an area on the screen 4. How do we create an area on the screen

- a window - for our image?- a window - for our image? 5. How much of our infinite pad will 5. How much of our infinite pad will

appear on the screen?appear on the screen? 6. How long will the image remain on the 6. How long will the image remain on the

screen?screen?

CS 480/680 15Chapter 2 -- Graphics Programming

1.2 Coordinate Systems1.2 Coordinate Systems Originally, graphics systems required Originally, graphics systems required

the user to specify all information, such the user to specify all information, such as vertex locations, directly in units of as vertex locations, directly in units of the display devicethe display device

The advent of device independent The advent of device independent graphics freed application programmers graphics freed application programmers from worrying about the details of input from worrying about the details of input and output devices.and output devices.

At some point the values in the world At some point the values in the world coordinates must be mapped into device coordinates must be mapped into device coordinates. But the graphics system, coordinates. But the graphics system, rather than the user, is responsible for rather than the user, is responsible for this task.this task.

CS 480/680 16Chapter 2 -- Graphics Programming

2. The OpenGL API2. The OpenGL API

Before completing our program, we Before completing our program, we describe the OpenGL API in more detail.describe the OpenGL API in more detail.

In this chapter, we concentrate on how In this chapter, we concentrate on how we specify primitives to be displayed; we specify primitives to be displayed; We leave interaction to Chapter 3We leave interaction to Chapter 3

Note:Note: Our goal is to study computer graphics; we Our goal is to study computer graphics; we

are using an API to help us attain that goal.are using an API to help us attain that goal. Consequently, we do not present all OpenGL Consequently, we do not present all OpenGL

functions functions

CS 480/680 17Chapter 2 -- Graphics Programming

2.1 Graphics Functions2.1 Graphics Functions We can divide the functions in the We can divide the functions in the

API into groups based upon their API into groups based upon their functionality:functionality:

1. The primitive functions,1. The primitive functions, 2. Attribute functions,2. Attribute functions, 3. Viewing functions,3. Viewing functions, 4. Transformation functions,4. Transformation functions, 5. Input functions,5. Input functions, 6. Control functions.6. Control functions.

CS 480/680 18Chapter 2 -- Graphics Programming

2.2 The OpenGL Interface2.2 The OpenGL Interface OpenGL function names begin with the OpenGL function names begin with the

letters gl and are stored in a library letters gl and are stored in a library usually referred to as GLusually referred to as GL

There are a few related libraries that we There are a few related libraries that we also use:also use:

graphics utility library (GLU)graphics utility library (GLU) GL Utility Toolkit (GLUT)GL Utility Toolkit (GLUT)

CS 480/680 19Chapter 2 -- Graphics Programming

3. Primitives and 3. Primitives and AttributesAttributes

Within the graphics community, there Within the graphics community, there has been an ongoing debate:has been an ongoing debate: API’s should contain a small set of API’s should contain a small set of

primitives (minimalist position) that ALL primitives (minimalist position) that ALL hardware can be expected to support.hardware can be expected to support.

API’s should have everything hardware can API’s should have everything hardware can support.support.

CS 480/680 20Chapter 2 -- Graphics Programming

OpenGL takes an intermediate positionOpenGL takes an intermediate position The basic library has a small set of primitives.The basic library has a small set of primitives. GLU contains a richer set of objects (derived)GLU contains a richer set of objects (derived)

The basic OpenGL primitives are specified The basic OpenGL primitives are specified via points in space. Thus, the programmer via points in space. Thus, the programmer defined their objects with sequences of the defined their objects with sequences of the form:form:

glBegin(type);glBegin(type); glVertex*(...);glVertex*(...); ...... glVertex*(...);glVertex*(...); glEnd();glEnd();

The value of type specifies how OpenGL The value of type specifies how OpenGL interprets the verticesinterprets the vertices

CS 480/680 21Chapter 2 -- Graphics Programming

If we wish to display line segments, we If we wish to display line segments, we have a few choices in OpenGL. have a few choices in OpenGL.

The primitives and their type The primitives and their type specifications include:specifications include:

Line SegmentsLine Segments GL_LINESGL_LINES

PolylinesPolylines GL_LINE_STRIPGL_LINE_STRIP GL_LINE_LOOPGL_LINE_LOOP

CS 480/680 22Chapter 2 -- Graphics Programming

3.1 Polygon Basics3.1 Polygon Basics Def: PolygonDef: Polygon

Polygons play a special role in computer Polygons play a special role in computer graphics because:graphics because:

we can display them rapidly and we can display them rapidly and we can use them to approximate curved we can use them to approximate curved

surfaces.surfaces.

The performance of graphics systems is The performance of graphics systems is measured in the number o polygons per measured in the number o polygons per second that can be displayedsecond that can be displayed

CS 480/680 23Chapter 2 -- Graphics Programming

We can display a polygon in a We can display a polygon in a variety of ways.variety of ways. Only its edges,Only its edges, Fill its interior with a solid colorFill its interior with a solid color Fill its interior with a pattern.Fill its interior with a pattern. We can display or not display the edgesWe can display or not display the edges

CS 480/680 24Chapter 2 -- Graphics Programming

Def: Simple PolygonDef: Simple Polygon

Def: ConvexityDef: Convexity

CS 480/680 25Chapter 2 -- Graphics Programming

In three dimensions polygons present a In three dimensions polygons present a few more difficulties because they are not few more difficulties because they are not necessarily flat.necessarily flat.

3 non-collinear points define a triangle ad a 3 non-collinear points define a triangle ad a plane the triangle lies in.plane the triangle lies in.

Often we are almost forced to use triangles Often we are almost forced to use triangles because typical rendering algorithms are because typical rendering algorithms are guaranteed to be correct only if the vertices guaranteed to be correct only if the vertices form a flat convex polygon.form a flat convex polygon.

In addition, hardware and software often In addition, hardware and software often support a triangle type that is rendered support a triangle type that is rendered much faster than a polygon with three much faster than a polygon with three vertices.vertices.

CS 480/680 26Chapter 2 -- Graphics Programming

3.2 Polygon Types in OpenGL3.2 Polygon Types in OpenGL PolygonsPolygons

GL_POLYGONGL_POLYGON Triangles and QuadrilateralsTriangles and Quadrilaterals

GL_TRIANGLESGL_TRIANGLES GL_QUADSGL_QUADS

Strips and FansStrips and Fans GL_TRIANGLE_STRIPGL_TRIANGLE_STRIP GL_QUAD_STRIPGL_QUAD_STRIP GL_TRIANGLE_FANGL_TRIANGLE_FAN

CS 480/680 27Chapter 2 -- Graphics Programming

3.3 Text3.3 Text Stroke TextStroke Text

Postscript -- font is defined by polynomial Postscript -- font is defined by polynomial curvescurves

Requires processing power and memoryRequires processing power and memory so printer typically has a CPU and so printer typically has a CPU and

memorymemory

CS 480/680 28Chapter 2 -- Graphics Programming

Raster TextRaster Text Simple and FastSimple and Fast

You can increase the size by replicating You can increase the size by replicating pixelspixels

CS 480/680 29Chapter 2 -- Graphics Programming

OpenGLOpenGL Because stroke and bitmap characters can be Because stroke and bitmap characters can be

created from other primitives, OpenGL does created from other primitives, OpenGL does not have a text primitivenot have a text primitive

However, GLUT provides a few bitmap and However, GLUT provides a few bitmap and stroke character sets that are defined in stroke character sets that are defined in software.software.

glutBitmapCharacter(GLUT_BITMAP_8_BY_glutBitmapCharacter(GLUT_BITMAP_8_BY_13, c)13, c)

We will return to text in Chapter 3.We will return to text in Chapter 3. There we shall see that both stroke and raster There we shall see that both stroke and raster

texts can be implemented most efficiently texts can be implemented most efficiently through display lists.through display lists.

CS 480/680 30Chapter 2 -- Graphics Programming

3.4 Curved Objects3.4 Curved Objects The primitives in our basic set have all The primitives in our basic set have all

been defined through vertices.been defined through vertices. We can take two approaches to creating a We can take two approaches to creating a

richer set of objects.richer set of objects. 1. We can use the primitives that we have to 1. We can use the primitives that we have to

approximate curves and surfaces.approximate curves and surfaces. If we want a circle, we can use a regular If we want a circle, we can use a regular

polygon of n surfaces.polygon of n surfaces. If we want a sphere, we can approximate it If we want a sphere, we can approximate it

with a regular polyhedronwith a regular polyhedron More generally, we approximate a curved More generally, we approximate a curved

surface by a mesh of convex polygons (a surface by a mesh of convex polygons (a tessellation).tessellation).

CS 480/680 31Chapter 2 -- Graphics Programming

2. The other approach, which we explore in 2. The other approach, which we explore in Chapter 10, is to start with the mathematical Chapter 10, is to start with the mathematical definitions of curved objects, and then to build definitions of curved objects, and then to build graphic functions to implement those objects.graphic functions to implement those objects.

Most graphics systems provide aspects of both Most graphics systems provide aspects of both approaches.approaches.

We can use GLU for a collection of We can use GLU for a collection of approximations to common curved approximations to common curved surfaces.surfaces.

And, we can write functions to define more And, we can write functions to define more of our own.of our own.

CS 480/680 32Chapter 2 -- Graphics Programming

3.5 Attributes3.5 Attributes In a modern graphics system, there is a In a modern graphics system, there is a

distinction between what type of a distinction between what type of a primitive is and how that primitive is primitive is and how that primitive is displayeddisplayed

A red solid line and a green dashed line A red solid line and a green dashed line are the same geometric type, but each is are the same geometric type, but each is displayed differently.displayed differently.

An attribute is any property that An attribute is any property that determines how a geometric primitive is determines how a geometric primitive is rendered.rendered.

Color, thickness, patternColor, thickness, pattern

CS 480/680 33Chapter 2 -- Graphics Programming

Attributes may be associates with, or Attributes may be associates with, or bound to, primitives at various points in bound to, primitives at various points in the modeling rendering pipeline.the modeling rendering pipeline.

Bindings may not be permanent.Bindings may not be permanent.

In immediate mode, primitives are not In immediate mode, primitives are not stored in the system, but rather are stored in the system, but rather are passed through the system for possible passed through the system for possible display as soon as they are defined.display as soon as they are defined.

They are not stored in memory, and once They are not stored in memory, and once erased from the screen, they are gone.erased from the screen, they are gone.

CS 480/680 34Chapter 2 -- Graphics Programming

4. Color4. Color

Color is one of the most interesting Color is one of the most interesting aspects of both human perception and aspects of both human perception and computer graphicscomputer graphics

Color in computer graphics is based on Color in computer graphics is based on what has become known as the three-what has become known as the three-color theorycolor theory

CS 480/680 35Chapter 2 -- Graphics Programming

A good analogy is to consider three A good analogy is to consider three colored spotlights.colored spotlights.

We can attempt to match any color by We can attempt to match any color by adjusting the intensities of the individual adjusting the intensities of the individual spotlights.spotlights.

Although we might not be able to match all Although we might not be able to match all colors in this way, if we use red green and colors in this way, if we use red green and blue we can come close.blue we can come close.

CS 480/680 36Chapter 2 -- Graphics Programming

The three colors stems from our eyes.The three colors stems from our eyes. The color receptors in our eyes - the The color receptors in our eyes - the

cones - are three different types.cones - are three different types. Thus the brain perceives the color Thus the brain perceives the color

through a triplet, rather than a through a triplet, rather than a continuous distribution.continuous distribution.

The basic tenet of three-color theory:The basic tenet of three-color theory: if two colors produce the same if two colors produce the same

tristimulus values, then they are visually tristimulus values, then they are visually indistinguishable.indistinguishable.

CS 480/680 37Chapter 2 -- Graphics Programming

We can view a color as a point in a We can view a color as a point in a color solid as shown here:color solid as shown here:

CS 480/680 38Chapter 2 -- Graphics Programming

We are looking at additive color systems We are looking at additive color systems because of the way computer display because of the way computer display systems work. systems work.

There is also a subtractive color model which There is also a subtractive color model which is typically used in commercial printing and is typically used in commercial printing and painting.painting.

In subtractive systems, the primaries are In subtractive systems, the primaries are usually the complementary colors: cyan usually the complementary colors: cyan magenta, and yellowmagenta, and yellow

CS 480/680 39Chapter 2 -- Graphics Programming

4.1 RGB Color4.1 RGB Color Now we can look at how color is Now we can look at how color is

handled in a graphics system from handled in a graphics system from the programmer’s perspective -- that the programmer’s perspective -- that is, through the APIis, through the API In the three-primary-color, additive-color In the three-primary-color, additive-color

RGB systems, there are conceptually RGB systems, there are conceptually separate frame buffers for red, green, separate frame buffers for red, green, and blueand blue

CS 480/680 40Chapter 2 -- Graphics Programming

Because the API should be Because the API should be independent of the particulars of the independent of the particulars of the hardware, we will use the color cube, hardware, we will use the color cube, and specify numbers between 0.0 and and specify numbers between 0.0 and 1.01.0

In OpenGL, we use the color cube as In OpenGL, we use the color cube as follows. follows. To draw in red, we issue the function callTo draw in red, we issue the function call

glColor3f(1.0, 0.0, 0.0);glColor3f(1.0, 0.0, 0.0);

CS 480/680 41Chapter 2 -- Graphics Programming

Later, we shall be interested in a four-Later, we shall be interested in a four-color (RGBA) system.color (RGBA) system.

In Chapter 9, we shall see various uses of the In Chapter 9, we shall see various uses of the Alpha channel, such as for creating fog Alpha channel, such as for creating fog effects or for combining images.effects or for combining images.

The alpha value will be treated by OpenGL as The alpha value will be treated by OpenGL as an opacity or transparency value.an opacity or transparency value.

For now we can use it to clear our For now we can use it to clear our drawing window.drawing window.

glClearColor(1.0, 1.0, 1.0, 1.0);glClearColor(1.0, 1.0, 1.0, 1.0); We can then use the function glClear to make We can then use the function glClear to make

the window solid and white.the window solid and white.

CS 480/680 42Chapter 2 -- Graphics Programming

4.2 Indexed Color4.2 Indexed Color Many systems have frame buffers that Many systems have frame buffers that

are limited in depth.are limited in depth. If we choose a limited number of colors If we choose a limited number of colors

from a large selection, we should be able to from a large selection, we should be able to create good quality images most of the time.create good quality images most of the time.

Historically color-index mode was important because it Historically color-index mode was important because it required less memory for the frame buffer.required less memory for the frame buffer.

For most of our code we will use a standard RGB For most of our code we will use a standard RGB model.model.

CS 480/680 43Chapter 2 -- Graphics Programming

4.3 Setting of Color Attributes4.3 Setting of Color Attributes The first color to set is the clear colorThe first color to set is the clear color

glClearColor(1.0,1.0,1.0,1.0);glClearColor(1.0,1.0,1.0,1.0);

We can select the rendering color for our We can select the rendering color for our points by setting the color variable points by setting the color variable

glColor3f(1.0,0.0,0.0);glColor3f(1.0,0.0,0.0);

We can set the size of our rendered points to We can set the size of our rendered points to be 2 pixels wide, by using be 2 pixels wide, by using

glPointSize(2.0);glPointSize(2.0);

Note that attributes such as point size and Note that attributes such as point size and line width are specified in terms of the line width are specified in terms of the pixel size.pixel size.

CS 480/680 44Chapter 2 -- Graphics Programming

5. Viewing5. Viewing

Just as the casual photographer does Just as the casual photographer does not need to worry about how the not need to worry about how the shutter works or what are the details of shutter works or what are the details of the photochemical interaction of light the photochemical interaction of light and film is, and film is,

So the application programmer only So the application programmer only needs to worry about the specifications needs to worry about the specifications of the objects and the camera.of the objects and the camera.

CS 480/680 45Chapter 2 -- Graphics Programming

5.1 Two-Dimensional Viewing5.1 Two-Dimensional Viewing taking a rectangular area of our two-taking a rectangular area of our two-

dimensional world and transferring its dimensional world and transferring its contents to the display as shown:contents to the display as shown:

CS 480/680 46Chapter 2 -- Graphics Programming

Remember that two-dimensional graphics Remember that two-dimensional graphics is a special case of three-dimensional is a special case of three-dimensional graphics.graphics.

Our viewing rectangle is the plane z=0 Our viewing rectangle is the plane z=0 within a three-dimensional viewing volume.within a three-dimensional viewing volume.

If we do not specify a viewing volume, If we do not specify a viewing volume, OpenGL uses its default, a 2x2x2 cube with OpenGL uses its default, a 2x2x2 cube with the origin at the center.the origin at the center.

CS 480/680 47Chapter 2 -- Graphics Programming

5.2 The Orthographic View5.2 The Orthographic View This two-dimensional view is a special This two-dimensional view is a special

case of the orthographic projection case of the orthographic projection (discussed more in Chapter 5)(discussed more in Chapter 5)

points at (x,y,z) are projected to (x,y,0)points at (x,y,z) are projected to (x,y,0)

CS 480/680 48Chapter 2 -- Graphics Programming

In OpenGL, an orthographic projection is In OpenGL, an orthographic projection is specified viaspecified via

void glOrtho(Gldouble left, Gldouble right, void glOrtho(Gldouble left, Gldouble right, Gldouble bottom, Gldouble top, Gldouble Gldouble bottom, Gldouble top, Gldouble near, Gldouble far);near, Gldouble far);

Unlike a real camera, the orthographic Unlike a real camera, the orthographic projection can include objects behind the cameraprojection can include objects behind the camera

void glOrtho2D(Gldouble left, Gldouble right, void glOrtho2D(Gldouble left, Gldouble right, Gldouble bottom, Gldouble top);Gldouble bottom, Gldouble top);

In Chapters 4 and 5 we will discuss moving the In Chapters 4 and 5 we will discuss moving the camera and creating more complex views.camera and creating more complex views.

CS 480/680 49Chapter 2 -- Graphics Programming

5.3 Matrix Modes5.3 Matrix Modes The two most important matrices are The two most important matrices are

the model-view and the model-view and projection matrices. projection matrices.

In Chapter 4 we will study functions to In Chapter 4 we will study functions to manipulate these matricesmanipulate these matrices

The following is common for setting a two-The following is common for setting a two-dimensional viewing rectangle:dimensional viewing rectangle:

glMatrixMode(GL_PROJECTION);glMatrixMode(GL_PROJECTION); glLoadIdentity();glLoadIdentity(); gluOrtho2D(0.0,500.0, 0.0, 500.0);gluOrtho2D(0.0,500.0, 0.0, 500.0); glMatrixMode(GL_MODELVIEW);glMatrixMode(GL_MODELVIEW);

This defines a 500x500 viewing rectangle, This defines a 500x500 viewing rectangle, with the lower-left corner as the origin.with the lower-left corner as the origin.

CS 480/680 50Chapter 2 -- Graphics Programming

6. Control Functions6. Control Functions

We are almost done with our first We are almost done with our first program,program, but we must still discuss interaction with but we must still discuss interaction with

the window and operating systems.the window and operating systems.

Rather than deal with these issues in detail Rather than deal with these issues in detail we will look at the simple interface GLUT we will look at the simple interface GLUT provides.provides.

Applications produced using GLUT should run Applications produced using GLUT should run under multiple window systems.under multiple window systems.

CS 480/680 51Chapter 2 -- Graphics Programming

6.1 Interaction with the Window 6.1 Interaction with the Window SystemSystem

Before we can open a window, there must be Before we can open a window, there must be interaction between the windowing system interaction between the windowing system and OpenGL. and OpenGL.

glutInit(int *argcp, char **argv)glutInit(int *argcp, char **argv) glutCreateWindow(char *title)glutCreateWindow(char *title) glutInitDisplayMode(GLUT_RGB | glutInitDisplayMode(GLUT_RGB |

GLUT_DEPTH | GLUT_DOUBLE);GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(480, 640);glutInitWindowSize(480, 640); glutInitWindowPosition(0,0);glutInitWindowPosition(0,0);

CS 480/680 52Chapter 2 -- Graphics Programming

6.2 Aspect Ratio and Viewports6.2 Aspect Ratio and Viewports Def: Aspect RatioDef: Aspect Ratio If the ratio of the viewing rectangle If the ratio of the viewing rectangle

(specified by glOrtho) is not the same as (specified by glOrtho) is not the same as the aspect ratio specified by the aspect ratio specified by glutInitWindowSize, you can end up with glutInitWindowSize, you can end up with distortion on the screen.distortion on the screen.

CS 480/680 53Chapter 2 -- Graphics Programming

A viewport is a rectangular area of the A viewport is a rectangular area of the display window. display window.

By default, it is the entire window, but it can By default, it is the entire window, but it can be set to any smaller size.be set to any smaller size.

Void glViewport(Glint x, Glint y, Glsizei w, Void glViewport(Glint x, Glint y, Glsizei w, Glsizei h)Glsizei h)

We will see further uses of the viewport in We will see further uses of the viewport in Chapter 3, where we consider interactive Chapter 3, where we consider interactive changes in the size and shape of the windowchanges in the size and shape of the window

CS 480/680 54Chapter 2 -- Graphics Programming

6.3 The main, display, and myinit 6.3 The main, display, and myinit FunctionsFunctions

In Chapter 3 we will discuss event In Chapter 3 we will discuss event processing, which will give us processing, which will give us tremendous control in our programs. tremendous control in our programs. For now, we can use the GLUT functionFor now, we can use the GLUT function

void glutMainLoop(void);void glutMainLoop(void);

Graphics are sent to the screen through Graphics are sent to the screen through a function called a display callback. a function called a display callback.

This function is specified through the GLUT This function is specified through the GLUT function function

void glutDisplayFunc(void (*func)(void));void glutDisplayFunc(void (*func)(void));

CS 480/680 55Chapter 2 -- Graphics Programming

#include <GL/glut.h>#include <GL/glut.h> void main(int argc, char **argv)void main(int argc, char **argv) {{ glutInit(&argc, argv);glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | glutInitDisplayMode(GLUT_SINGLE |

GLUT_RGB);GLUT_RGB); glutInitWindowSize(500,500);glutInitWindowSize(500,500); glutInitWindowPosition(0,0);glutInitWindowPosition(0,0); glutCreateWindow(“simple OpeGL example);glutCreateWindow(“simple OpeGL example); glutDisplayFunc(display);glutDisplayFunc(display); myinit();myinit(); glutMainLoop();glutMainLoop(); }}

CS 480/680 56Chapter 2 -- Graphics Programming

6.4 Program Structure6.4 Program Structure Every program we write will have the Every program we write will have the

same structure as our gasket program.same structure as our gasket program. We will always use the GLUT toolkitWe will always use the GLUT toolkit The main function will then consist of calls The main function will then consist of calls

to GLUT functions to set up our window(s) to GLUT functions to set up our window(s) The main function will also name the The main function will also name the

required callbacksrequired callbacks every program must have a display every program must have a display

callbackcallback most will have other callbacks to set up most will have other callbacks to set up

interaction.interaction. The myinit will set up user options The myinit will set up user options

(usually calls to GL and GLU library (usually calls to GL and GLU library functions.)functions.)

CS 480/680 57Chapter 2 -- Graphics Programming

7. The Gasket Program7. The Gasket Program

Using the previous program as our base Using the previous program as our base We can now write the myinit function and We can now write the myinit function and

the display function for our Sierpinski the display function for our Sierpinski gasketgasket

We will draw red points on a white We will draw red points on a white backgroundbackground

all within a 500x500 square.all within a 500x500 square.

CS 480/680 58Chapter 2 -- Graphics Programming

void myinit(void)void myinit(void) {{ glClearColor(1.0,1.0,1.0,0.0;glClearColor(1.0,1.0,1.0,0.0; glColor3f(1.0,0.0,0.0);glColor3f(1.0,0.0,0.0); glMatrixMode(GL_PROJECTION);glMatrixMode(GL_PROJECTION); gluLoadIdentity();gluLoadIdentity(); gluOrtho2D(0.0,500.0,0.0,500.0);gluOrtho2D(0.0,500.0,0.0,500.0); glMatrixMode(GL_MODELVIEW);glMatrixMode(GL_MODELVIEW); }}

CS 480/680 59Chapter 2 -- Graphics Programming

void display(void)void display(void) {{ typedef Glfoat point2[2];typedef Glfoat point2[2]; point2 vertices[3]={{0.0,0.0},{250.0,500.0},point2 vertices[3]={{0.0,0.0},{250.0,500.0},

{500.0,0.0}};{500.0,0.0}}; int i,j,k;int i,j,k; point2 p={75.0,50.0};point2 p={75.0,50.0}; glClear(GL_COLOR_BUFFER_BIT);glClear(GL_COLOR_BUFFER_BIT); for(k=0;k<5000;k++){for(k=0;k<5000;k++){ j=rand()%3;j=rand()%3; p[0]=(p[0]+vertices[j][0])/2.0;p[0]=(p[0]+vertices[j][0])/2.0; p[1]=(p[1]+vertices[j][1])/2.0;p[1]=(p[1]+vertices[j][1])/2.0; glBegin(GL_POINTS)glBegin(GL_POINTS) glVertex2fv(p);glVertex2fv(p); glEnd();glEnd(); }} glFlush();glFlush(); }}

CS 480/680 60Chapter 2 -- Graphics Programming

8. Polygons and 8. Polygons and RecursionRecursion

We can generate the gasket a different way We can generate the gasket a different way bisecting the edges of the trianglebisecting the edges of the triangle

and doing this over recursively until we and doing this over recursively until we reach the desired subdivision levelreach the desired subdivision level

CS 480/680 61Chapter 2 -- Graphics Programming

Let us start our code with a simple function Let us start our code with a simple function that draws a single triangular polygon with that draws a single triangular polygon with three arbitrary vertices.three arbitrary vertices.

void triangle(point2 a, point2 b, point2 c)void triangle(point2 a, point2 b, point2 c) {{ glBegin(GL_TRIANGLES);glBegin(GL_TRIANGLES); glVertex2fv(a);glVertex2fv(a); glVertex2fv(b);glVertex2fv(b); glVertex2fv(c);glVertex2fv(c); glEnd();glEnd(); }}

CS 480/680 62Chapter 2 -- Graphics Programming

void divide_triangle(point2 a, point2 b, point2 c, int void divide_triangle(point2 a, point2 b, point2 c, int k)k)

{{ point2 ab, ac bc;point2 ab, ac bc; int jint j if(k>0){if(k>0){ // compute the midpoints of the sides// compute the midpoints of the sides for(j=0;j<2;j++) ab[j]=(a[j]+b[j])/2;for(j=0;j<2;j++) ab[j]=(a[j]+b[j])/2; for(j=0;j<2;j++) ac[j]=(a[j]+c[j])/2;for(j=0;j<2;j++) ac[j]=(a[j]+c[j])/2; for(j=0;j<2;j++) bc[j]=(b[j]+c[j])/2;for(j=0;j<2;j++) bc[j]=(b[j]+c[j])/2;

// subdivide all but the inner triangle// subdivide all but the inner triangle divide_triangle(a,ab,ac,k-1);divide_triangle(a,ab,ac,k-1); divide_triangle(c,ac,bc,k-1);divide_triangle(c,ac,bc,k-1); divide_triangel(b,bc,ab,k-1);divide_triangel(b,bc,ab,k-1); } } else triangle(a,b,c);else triangle(a,b,c); }}

CS 480/680 63Chapter 2 -- Graphics Programming

The display function is now almost trivial. It The display function is now almost trivial. It uses global value of n determined by the main uses global value of n determined by the main program to fix the number of subdivisional program to fix the number of subdivisional steps.steps.

void display(void)void display(void) {{ glClear(GL_COLOR_BUFFER_BIT);glClear(GL_COLOR_BUFFER_BIT); divide_triangle(v[0], v[1], v[2], n);divide_triangle(v[0], v[1], v[2], n); glFlush();glFlush(); }}

Note: Note: often we have no convenient way to pass variables to often we have no convenient way to pass variables to

OpenGL functions and callbacks other than through OpenGL functions and callbacks other than through global parameters.global parameters.

Although we prefer not to pass values in such a Although we prefer not to pass values in such a manner, because the form of these functions is fixed, manner, because the form of these functions is fixed, we have no good alternative.we have no good alternative.

CS 480/680 64Chapter 2 -- Graphics Programming

Here is the triangle when there are 5 Here is the triangle when there are 5 subdivisions.subdivisions.

CS 480/680 65Chapter 2 -- Graphics Programming

9. The Three-9. The Three-Dimensional GasketDimensional Gasket We have argued:We have argued:

that two-dimensional graphics is a special case that two-dimensional graphics is a special case of three-dimensional graphicsof three-dimensional graphics

But we have not yet seen a true three-But we have not yet seen a true three-dimensional program.dimensional program.

So, lets convert the Gasket program to So, lets convert the Gasket program to three-dimensions.three-dimensions.

We start by replacing the initial triangle with a We start by replacing the initial triangle with a tetrahedrontetrahedron

CS 480/680 66Chapter 2 -- Graphics Programming

9.1 Use of Three-Dimensional 9.1 Use of Three-Dimensional PointsPoints

The required changes are primarily in The required changes are primarily in the function displaythe function display

typedef Glfloat point3[3];typedef Glfloat point3[3]; point3 vertices[4]{{0.0,0.0,0.0}, point3 vertices[4]{{0.0,0.0,0.0},

{250.0,500.0,100.0}, {250.0,500.0,100.0}, {500.0,250.0,250.0}, {500.0,250.0,250.0}, {250.0,100.0,150.0)}};{250.0,100.0,150.0)}};

point3 p={250.0, 100.0, 250.0};point3 p={250.0, 100.0, 250.0};

We will also color the points to help visualize We will also color the points to help visualize its location.its location.

CS 480/680 67Chapter 2 -- Graphics Programming

CS 480/680 68Chapter 2 -- Graphics Programming

9.2 Use of Polygons in Three 9.2 Use of Polygons in Three DimensionsDimensions

Following our second approach, we note that Following our second approach, we note that the faces of a tetrahedron are the four the faces of a tetrahedron are the four triangles determined by its four vertices.triangles determined by its four vertices.

Our triangle function changes to:Our triangle function changes to:

void triangle(point3 a, point3 b, point3 c)void triangle(point3 a, point3 b, point3 c) {{ glBegin(GL_POLYGON);glBegin(GL_POLYGON); glVertex3fv(a);glVertex3fv(a); glVertex3fv(b);glVertex3fv(b); glVertex3fv(c);glVertex3fv(c); glEnd();glEnd(); }}

CS 480/680 69Chapter 2 -- Graphics Programming

Our divide triangle function just changes Our divide triangle function just changes from point2 to point3 parameters.from point2 to point3 parameters.

We then generate our subdivided We then generate our subdivided tetrahedrontetrahedron

void tetrahedron(int n)void tetrahedron(int n) {{ glColor3f(1.0,0.0,0.0);glColor3f(1.0,0.0,0.0); divide_triangle(v[0],v[1],v[2],k);divide_triangle(v[0],v[1],v[2],k); glColor3f(0.0,1.0,0.0);glColor3f(0.0,1.0,0.0); divide_triangle(v[3],v[2],v[1],k);divide_triangle(v[3],v[2],v[1],k); glColor3f(0.0,0.0,1.0);glColor3f(0.0,0.0,1.0); divide_triangle(v[0],v[3],v[1],k);divide_triangle(v[0],v[3],v[1],k); glColor3f(0.0,0.0,0.0);glColor3f(0.0,0.0,0.0); divide_triangle(v[0],v[2],v[3],k);divide_triangle(v[0],v[2],v[3],k); }}

CS 480/680 70Chapter 2 -- Graphics Programming

9.3 Hidden-Surface Removal9.3 Hidden-Surface Removal If you execute the code we just wrote, If you execute the code we just wrote,

you might be confusedyou might be confused the program draws the triangles in the order the program draws the triangles in the order

specified by the recursion, not by the specified by the recursion, not by the geometric relationship between the geometric relationship between the triangles.triangles.

Each triangle is drawn (filled) in a solid color Each triangle is drawn (filled) in a solid color and is drawn over those triangles already on and is drawn over those triangles already on the display.the display.

The issue is hidden surface removalThe issue is hidden surface removal

CS 480/680 71Chapter 2 -- Graphics Programming

For now, we can use the z-buffer For now, we can use the z-buffer algorithm supported by OpenGLalgorithm supported by OpenGL

glutInitDisplayMode(GLUT_SINGLE | glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);GLUT_RGB | GLUT_DEPTH);

glEnable(GL_DEPTH_TEST);glEnable(GL_DEPTH_TEST);

we must also clear the Depth Buffer in the we must also clear the Depth Buffer in the display function:display function:

void display()void display() {{ glClear(GL_COLOR_BUFFER_BIT | glClear(GL_COLOR_BUFFER_BIT |

GL_DEPTH_BUFFER_BIT);GL_DEPTH_BUFFER_BIT); tetrahedron(n);tetrahedron(n); glFlush();glFlush(); }}

CS 480/680 72Chapter 2 -- Graphics Programming

CS 480/680 73Chapter 2 -- Graphics Programming

10. Summary10. Summary

In this chapter, we introduced the In this chapter, we introduced the OpenGL API OpenGL API

The Sierpinski gasket provides a The Sierpinski gasket provides a nontrivial beginning applicationnontrivial beginning application more details abut Fractal Geometry are more details abut Fractal Geometry are

given in Chapter 11.given in Chapter 11. The historical development of graphics The historical development of graphics

API’s and graphical models illustrates API’s and graphical models illustrates the importance of starting in three the importance of starting in three dimensions.dimensions.

CS 480/680 74Chapter 2 -- Graphics Programming

11. Suggested Readings11. Suggested Readings

Pen Plotter API of Postscript and LOGOPen Plotter API of Postscript and LOGO GKS, GKS-3D, PHIGS, and PHIGS+ GKS, GKS-3D, PHIGS, and PHIGS+

API’sAPI’s The X Window SystemThe X Window System Renderman interfaceRenderman interface OpenGL Programming Guide, OpenGL OpenGL Programming Guide, OpenGL

Reference ManualReference Manual

CS 480/680 75Chapter 2 -- Graphics Programming

Exercises -- Due next Exercises -- Due next classclass