Вы находитесь на странице: 1из 146

Unit 2: Graphics Programming The OpenGL

By Shubha Raj K.B.

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

2.1 The Sierpinski Gasket


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

main() { initialize_the_system(); for (some_number_of_points) { pt=generate_a_point(); Display_the_point(pt); } Cleanup(); }


Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
4

2.2 Programming 2D Applications

Use pen-plotter API. P=(x,y,0) or p=(x,y) Or P can be represented by column matrix glVertex*() *= ntv

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

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

2.2.1 Co-ordinate Systems


The success of GL lead to OpenGL (1992), a platform-independent API that was
- Easy to use - Close enough to the hardware to get excellent performance - Focus on rendering - Omitted windowing and input to avoid window system dependencies

Device-independent graphics
- World or object co-ordinates - Device or Window or Screen co-ordinates

GS rather than the user is responsible for mapping.


Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
7

2.3 The OpenGL API


2.3.1 Graphics functions 2.3.2. The Graphics pipelines and state machines 2.3.3 The OpenGL interface: gl,glu, glut

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

The OpenGL API


OpenGL core library
- OpenGL32 on Windows - GL on most unix/linux systems (libGL.a)

OpenGL Utility Library (GLU)


- Provides functionality in OpenGL core but avoids having to rewrite code

Links with window system


- GLX for X window systems - WGL for Windows - AGL for Macintosh
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
9

Graphics System as a Black box


our basic model of a graphics package is a black box. This term is used to denote a system whose properties are described only by its
- inputs and outputs.

Graphics system is a box whose inputs are


- function calls from an application program; - measurements from input devices, such as the mouse and keyboard and messages from os.

Outputs are primarily the graphics sent to output devices Example


- Simplified view of inputs as function calls and - outputs as primitives.

Graphics system as a black box

Application program

function calls

output

Data

Graphics System

Input

Input/output devices

2.3.1 OpenGL Functions


7 different types of functions Primitives (WHAT)
- Points - Line Segments - 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

Primitive function
Define the low level objects or atomic entities that our system can display. Depending on the API, the primitives can include
- points, line segments, polygons, pixels, text , and various type of curves and surfaces.

Example glBegin(GL_POINTS); glVertex2f(100.0,200.0); glEnd(); glBegin(GL_LINES); glVertex2f(100.0,200.0); glVertex2f(300.0,400.0); glEnd();

Attribute function
To perform operations ranging from choosing the color with which we display a line segment.
- Eg glColor3f(1.0,0.0,0.0); glLineWidth(width);

To picking a pattern with which to fill the inside of a polygon. To selecting a typesafe for the title on a graph.

Viewing and transformation


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

Input function Allows us to deal with the diverse forms of input that characterize modern graphics systems.
- void glutKeyboardFunc(void (*func) (unsigned char key, int x, int y));

Control function Enable us to communicate with the window system, to initialize our programs and to deal with any errors that take place during the execution of our programs. - glutInitWindowSize(500,500);

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

The graphics pipeline and state machine


Entire graphics system is a state machine. A black box that contains a finite 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.3.2 The Graphics Pipeline and State Machines


OpenGL is a state machine OpenGL functions are of two types
- Primitive generating
Can cause output if primitive is visible How vertices are processed and appearance of primitive are controlled by the state

- State changing
Transformation functions Attribute functions

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

19

From the Pesspective of API, Two types of graphics functions:


1. Those that define primitives that flow through a pipeline inside the state machine
glVertex- first type

2. Those that either changes the state inside the machine or return state information.

In openGL most parameters are persistent.


Their values remain unchanged until we explicitly change them through functions that alter the state.
For example, once we set a color, that color remains the current color until it is changed through a color-altering function

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

2.3.3 OpenGL interface


Three libraries
- GL library - 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

GLU
- This library uses only GL functions but contains code for creating common objects and simplifying viewing. - 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, we need at least one more library.

GLX : OpenGL Extension for the X Window System


- For the X window system, this library is called GLX WGL for windows, it is wgl - WGL or Wiggle is the windowing system interface to the Microsoft Windows implementation of the OpenGL specification .

AGL
- for the macintosh it is agl or(Apple graphics library).

Rather than using a different library for each system,we use a readily available library called the openGL utility Toolkit(GLUT). GLUT provides minimum functionality that should be expected in any modern windowing system.

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

Library organization for an xwindows system environment

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

26

OpenGL #defines
Most constants are defined in the include files gl.h, glu.h and glut.h
- Note #include <GL/glut.h> should automatically include the others - Examples -glBegin(GL_POLYGON) -glClear(GL_COLOR_BUFFER_BIT)

include files also define OpenGL data types: GLfloat, GLdouble,.


Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
27

2.4 PRIMITIVES AND ATTRIBUTES

OpenGL supports two classes of primitives:


- Geometric primitives - Image (or) raster primitives Geometric primitives Include points, line segments, polygons, curves and surfaces. These primitives pass through a geometric pipeline.
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.

Primitives and Attributes


Minimal set Other set OpenGL supports 2 classes of primitives
- Geometric primitives - Image or Raster primitives

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

30

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

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

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

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

All the basic types are defined by sets of vertices.

LINE SEGMENTS Finite sections of lines between two vertices called line segments.
USES Use line segments to define approximations to curves. 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.

The primitive and their type specification include the following:


Points(GL_POINTS):
- Each vertex is displayed at a size of at least one pixel.

Line segments(GL_LINES):
- Successive pairs of vertices to be interpreted as the endpoints of individual segments.

Polylines(GL_LINE_STRIP,GL_LINE_LOOP):
GL_LINE_STRIP - If successive vertices are to be connected, we can use the line strip or polyline form. GL_LINE_LOOP - will draw a line segment from the final vertex to the first, thus creating a closed path.

Polygon Basics
Polygon has a border and has a well defined interior.
- 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 rendering Render only its edges. Render its interior with a solid color or a pattern. we can render or not render the edges

Filled objects

Methods of displaying a polygon

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

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. p1 and p2 are arbitrary points inside a polygon and the entire line segment connecting them is inside the polygon. Convex objects include
triangle, tetrahedra, rectangles, circles, spheres, parallepipeds.

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

Polygon Issues
OpenGL will only display polygons correctly that are
- 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

User program can check if above true


- 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

a) Simple polygon B) Nonsimple polygon

Convexity

Convex objects

Polygon types in OpenGL


Polygons(GL_POLYGON):
- successive vertices define line segments and a line segment connects the final vertex to the first. - use the function glPolygonMode to tell the renderer to generate only the edges or just points for the vertices, instead of fill. - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

Triangle and quadrilaterals (GL_TRIANGLES,GL_QUADS):


- Successive groups of three and four vertices are interpreted as triangles and quadrilaterals.

Strips and Fans(GL_TRIANGLE_STRIP, GL_QUAD_STRIP, GL_TRIANGLE_FAN)


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

Polygon types

2.4.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.

2.4.4 TEXT
There are two forms of text:
- Stroke - Raster

Stroke text is constructed as are other geometric objects Advantage


- It can be defined to have all the detail of any other object. - It can be manipulated by our standard transformations. - Using transformation we can make a stroke character bigger or rotate

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

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

a)Raster text

b) Raster character replication

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

2.4.5 Curved objects


Two approaches
- We can use the primitives that we have to approximate curves and surfaces.
a circle with a regular polygon with n sides

- mathematical definitions of curved objects


supported by GLU library quadric surfaces, parametric polynomial curves and surfaces

2.4.5 Curved objects


1. Use the primitives that we have to approximate curves and surfaces Ex: Circle
- Sphere (Triangles and Quadrilaterals)

Tessellation
- We approximate a curves surfaces by a mesh of convex polygons- Tessellation - which can occur either at the
rendering stage or within the user programs

2. Start with the mathematical definitions of curved objects


Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
62

2.4.6 Attributes
Color Thinkness of a line Pattern used to fill a polygon

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

63

Attributes
An Attributes is any property that determines how a geometric primitive is to be rendered - point (color, size), line (color,thickness, type), polygon (pattern types, etc). - text (height, width, font, style (bold, italic, 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. no memory once erased from the display,it is lost. display list keep objects in memory so that these objects can be redisplayed.

Attributes
Attributes are part of the OpenGL state and determine the appearance of objects
- Color (points, lines, polygons) - Size and width (points, lines) - Stipple pattern (lines, polygons) - Polygon mode
Display as filled: solid color or stipple pattern Display edges Display vertices
65

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

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

Additive color model


- Primary colors add together to give the perceived color. - The primaries are red,green,blue(RGB) - Example of additive color include
CRT, projectors

Subractive color model


Primaries are complementary colors: Cyan, magenta, yellow(CMY) Example: commercial printing and painting

Additive color

Subtractive color

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

68

Color formation
Additive color Subtractive color

Color solid

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

2.5.1 RGB Color

There are separate buffers for


- red,green, and blue images.

Each pixel has separate red, green and blue components that correspond to locations in memory. Each pixel consist of 24 bits(3 bytes).
1 byte for each red, green and blue.

There are 224 possible colors-referred to as 16M colors.

Color components between 0.0 and 1.0, where 1.0 denotes the maximun(saturated value).
- glColor3f(1.0,0.0,0.0);

RGBA SYSTEM A-alpha The alpha value will be treated by OpenGL as either an opacity or transparency. A=0.0 - Fully transparent A=1.0 - Fully opaque

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

2.5.2 Indexed Color


Early graphics systems had frame buffers that were
- limited in depth.

Each pixel was 8 bits deep. Smaller group of pixel-assign to R,G,B.

It gives less no of color. Indexed color provide solution that allowed applications to display a wide range of color.
Images are called indexed color because the actual image color data for each pixel is the index into this palette . Analogy with an artist who paints in oil.

256 entries in the table constitute the users color palette. fig:color lookup table

Fig:Indexed color

2k-1. We can display colors with precision of m bits.


- we can choose from 2m reds,2m greens and 2m blues.

Suppose that our frame has k bits per pixel. Each pixel value or index is an integer between 0 and

We can produce any of 23m colors on the display,


- but the frame buffer can specify only 2k of them.

We handle the specification through a user defined color lookup table that is of size 2k *3m. The user program fills the 2k entries of the table with the desired colors ,
- using m bits for each of red ,green and blue.

The first RGB color in the table is index 0, the second RGB color is index 1, etc.
- There can be at most only 256 colors in the palette.

If we are in color index mode,


- the present color is selected by a function such as glIndexi(element); That selects a particular color out of the table.

GLUT allows us to set the


- entries in a color table for each window through the following function: glutSetColor(int color,GLfloat red,GLfloat green,GLfloat blue)

Advantage
- Less memory - Fewer other hardware components.

8-bit indexed images are still widely used to save


- bandwidth and - storage space.

When early computer screens were commonly limited to 256 colors,


- indexed color methods were essential.

2.5.3 Setting of color attributes


clear color glClearColor(1.0, 1.0, 1.0, 1.0); rendering color for points set to RED glColor3f(1.0, 0.0, 0.0); set point size let us use 2 pixels size glPointSize(2.0); These attributes will be valid for all the time if not changed explicitly.

2.6 VIEWING

Camera forms an image by exposing a film. The computer system forms an image
- by carrying out a sequence of operations in its pipeline.

The application program specifies


- parameters for object and the camera.

2.6.1 Orthographic view


Place the camera infinitely far from objects. Image plane is fixed, move camera far from this plane. All projectors become parallel and
- the center of projection is replaced by direction of projection.

Projectors that are parallel to the positive


- z-axis and the projection plane at z=0.

Projectors are perpendicular or orthogonal to the projection plane.

Slide the projection plane along the z-axis without changing where the projectors intersect the plane.

Orthographic Projection
Projectors are orthogonal to projection surface

For orthographic viewing,


- special orthographic camera resides in the projection plane.

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. camera points in the negative z-direction.

The default camera and an orthographic view volume

Viewing volume

It takes a point(x,y,z) and projects it into the point(x,y,0). In openGL, an orthographic projection with a right parallelepiped viewing volume is specified via the following
void glOrtho(GLdouble left, GLdouble right, GLdouble bottom,GLdouble top, Gldouble near,GLdouble far);

All parameters are distances measured from the camera.

The orthographic projection sees only those objects in the volume specified by viewing volume.

If we do not specify a viewing volume,


- openGL uses its default, 2 x 2 x 2 cube, with the origin in the center.

In 2D plane, the bottom-left corner is


- at (-1.0,-1.0) and upper corner is at(1.0,1.0).

2.6.2 2D viewing
void gluOrtho2D (GLdouble left, Gldouble right, GLdouble bottom, GLdouble top)

Near and far set to -1.0 and 1.0 respectively.

Take a rectangular area of our two dimensional world and transferring its contents to the display.
The area of the world that we image is known as viewing rectangle or clipping rectangle. Objects inside the rectangle are in the image.
- objects outside are clipped out.

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

Two- and threedimensional viewing


In glOrtho(left, right, bottom, top, near, 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, we can use the function gluOrtho2D(left, right,bottom,top) In two dimensions, the view or clipping volume becomes a clipping window
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
95

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

2.6.3 Matrix Modes


In OpenGL, 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);

Transformation functions are incremental


- so we start with an identity matrix and alter it with a projection matrix that gives the view volume
glMatrixMode (GL_PROJECTION) glLoadIdentity(); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); glMatrixMode (GL_MODELVIEW)
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
97

Perspective projection

void glFrustum(GLdouble left, GLdouble right, GLdouble bottom,GLdouble top, GLdouble near, GLdouble far);

Orthographic projection

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

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 rectangles 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

Viewports
Do not have use the entire window for the image: glViewport(x,y,w,h) Values in pixels (screen coordinates)

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

105

Interaction between windowing system and OpenGL is initialized by the following function.
glutInit(int *argc,char **argv) Argument is same as main.

Open OpenGL window using GLUT function glutCreateWindow(char *title)


- Where the Title at the top of the window is given by string title.

Use following GLUT functions before window creation to specify these parameters.
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(640,480); glutInitWindowPosition(0,0);

Specifies a 480 x 640 window in the top-left corner of the display.

A Simple Program
Generate a square on a solid background

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

107

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

Event Loop
Note that the program defines a display callback function named mydisplay
- Every glut program must have a display callback - The display callback is executed whenever OpenGL decides the display must be refreshed,
for example when the window is opened

- The main function ends with the program entering an event loop
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
109

main.c
#include <GL/glut.h>

includes gl.h

int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("simple"); define window properties glutDisplayFunc(mydisplay);

init();
glutMainLoop(); }

display callback set OpenGL state enter event loop


110

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

init.c
black clear color opaque window

void init() { glClearColor (0.0, 0.0, 0.0, 1.0);


glColor3f(1.0, 1.0, 1.0);

fill/draw with white

glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); }

viewing volume
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
111

2.7.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

- callbacks
Display function Input and window functions
112

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

simple.c revisited
In this version, we shall see the same output
- but we have defined all the relevant state values through function calls
using the default values

In particular, we set
- Colors - Viewing conditions - Window properties
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
113

GLUT functions
glutInit allows application to get command line arguments and initializes system gluInitDisplayMode requests properties for the window (the rendering context)
- RGB color - Single buffering - 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

Coordinate Systems
The units in glVertex are determined by the application and are called
- object or problem coordinates

The viewing specifications are also in object coordinates and


- it is the size of the viewing volume that determines what will appear in the image

Internally, 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

2.8 THA GASKET PROGRAM


void myinit(void) { /* attributes */ glClearColor(1.0, 1.0, 1.0, 1.0); /* white background */ glColor3f(0.0, 0.0, 1.0); /* draw in red */ /* set up viewing */ /* 500 x 500 window with origin lower left */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 500.0, 0.0, 500.0); glMatrixMode(GL_MODELVIEW); }
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
116

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

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

117

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
- the area goes to zero - but the perimeter goes to infinity

This is not an ordinary geometric object


- It is neither two- nor three-dimensional

It is a fractal (fractional dimension) object


Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
120

Gasket Program
#include <GL/glut.h> /* initial triangle */ GLfloat v[3][2]={{-1.0, -0.58}, {1.0, -0.58}, {0.0, 1.15}}; int n; /* number of recursive steps */

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

121

Draw one triangle


void triangle( GLfloat *a, GLfloat *b, GLfloat *c) /* display one triangle { glVertex2fv(a); glVertex2fv(b); glVertex2fv(c); } */

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

122

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

display and init Functions


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

main Function
int main(int argc, char **argv) { n=4; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500, 500); glutCreateWindow(2D Gasket"); glutDisplayFunc(display); myinit(); glutMainLoop(); }

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

125

Efficiency Note
By having the glBegin and glEnd in the display callback
- 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

Objectives
Develop a more sophisticated threedimensional example
- Sierpinski gasket: a fractal

Introduce hidden-surface removal

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

127

2.10 Three-dimensional Applications


In OpenGL, two-dimensional applications
- are a special case of three-dimensional graphics

Going to 3D
- Not much changes - Use glVertex3*( ) - Have to worry about the order in which polygons are drawn or use hidden-surface removal - Polygons should be simple, convex, flat
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
128

OpenGL function format


function name glVertex3f(x,y,z) x,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

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, we can start with a tetrahedron

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

130

2.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

triangle code
void triangle( GLfloat *a, GLfloat *b, GLfloat *c) { glVertex3fv(a); glVertex3fv(b); glVertex3fv(c); }

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

132

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

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

v[2], m);

v[1], m);
v[1], m);

v[3], m);

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

134

Almost Correct
Because the triangles are drawn in the order they are defined in the program,
- 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

2.10.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
- 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

Using the z-buffer algorithm


The algorithm uses an extra buffer, the z-buffer,
- to store depth information as geometry travels down the pipeline

It must be - Requested in main


glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH)

- Enabled in init or in main


glEnable(GL_DEPTH_TEST)

- Cleared in the display callback


glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
137

Surface vs Volume Subdvision


In our example,
- we divided the surface of each face

We could also divide the volume


- using the same midpoints

The midpoints define four smaller tetrahedrons,


- 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

Color and State


The color as set by glColor becomes part of the state and will be used until changed - 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

Smooth Color
Default is smooth shading - OpenGL interpolates vertex colors across visible polygons Alternative is flat 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. OpenGL works with 3 matrices: GL_MODELVIEW:
- this one is used to move vertex to model space.
- By default, the matrix mode is GL_MODELVIEW, which assumes everything you draw will be in one 3Dspace.

GL_PROJECTION:
- this one is used to convert 3D coordinate to 2D coordinate for final pixel position.

A computer monitor is a 2D surface. We need to transform 3D scene into 2D image in order to display it. GL_PROJECTION matrix is for this projection transformation GL_TEXTURE: this one is used to alter texture coordinates.

Matrix mode
Pipeline graphics system depends on
- multiplying together or Concatenating a number of transformation matrices to achieve the desired image of a primitive

Two important matrices:


- Model-view - Projection matrix - Which are initially set to identity matrix. - The usual sequence is to modify the initial identity matrix by applying sequence of transformations. - Select the matrix to which the operations apply by first setting the matrix mode, a variable that is set to one type of matrix that is also part of the state.

Concept behind this code??Unit4 and 5


Once you set the matrix mode, each subsequent operation is applied to that particular matrix mode and below it . glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1, 1, -1, 1, -1.0, 1.0); glTranslate( 100, 100, 100 ); glRotate( 45, 1, 0, 0 );
GL_PROJECTION_MATRIX = IDENTITY * ORTHOGRAPHIC_MATRIX * TRANSLATION_MATRIX * ROTATION_MATRIX.

2.11 Plotting Implicit Functions


The problem we are discussing here is
- How to display data defined by an Implicit function of the form g(x, y)=0 - Where the function g is known analytically such as
Equation for a unit circle centered at the origin g(x, 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, y) pairs connected by line segments.

Marching Squares
- Solve the problem for sampled data by a technique called marching Squares
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
145

Summary of UNIT2
GKS
- 2D, Pen-Plotter Model - GKS-3D

PHIGS and PHIGS+


- 3D, Synthetic-Camera Model

OpenGL (Silicon Graphics Inc)


- From GL, Synthetic Camera Model with a Pipeline architecture - GL was designed specifically for high-speed real-time rendering.

Recently Sun Microsystems recently released their Java bindings for openGL
- Many Java programmer use the JOGL bindings

In chapter 10, discuss about scene Graphs,


- Which provide a much higher-level, OO interface to Graphics Hardware - Most scene graph APIs are built on top of openGL.

OpenGL (Scientific and engineering applications are written in openGL) DirectX??


- (Windows), Device-dependent features-from graphics Cards - Do not have the portability - GAME world

Modeling-rendering Paradigm
- Focus on Modeling in UNIT2
146

Angel: Interactive Computer Graphics 5E Addison-Wesley 2009

Вам также может понравиться