Unit 2: Computer Graphics

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 16

Computer Graphics

Unit 2
2.1 The OpenGL API
2.1.1 Graphics functions
Graphics system can be viewed as a box whose inputs are function calls from a user program
(say measurements from input devices, such as the mouse and keyboard and possibly other
input, such as messages from the operating system); the outputs are primarily the graphics
sent to the output devices.

An API is defined through the functions in its library.

A good API may contain hundreds of functions, so it is helpful to divide the functions into six
groups by their functionality:
1. The primitive functions define the low-level objects or atomic entities that the system
can display. The primitive includes points, line segments, polygons, pixels, text, and
various types of curves and surfaces. The primitives tells what the objects that can be
displayed,
2. The attributes govern the way that a primitive appears on the display. Attribute
functions perform operations ranging from choosing the color, to picking a pattern with
which to fill the inside of a polygon, to selecting a type face for the titles on a graph. The
attributes tells how the objects can be displayed
3. The viewing functions specify various views, position and orientation in its world, and
equivalent of a lens must also be selected. This process not only will fix the view, but also
clip out objects that are too close or too far away.
4. Transformation functions carry out transformations of objects, such as rotation,
translation, and scaling.
5. For interactive applications, the API provides a set of input functions to deal with
diverse forms of input that characterize modern graphics systems say functions to deal
with devices such as keyboards, mice, and data tablets.
6. The control functions help to communicate with the window system, to initialize the
programs, and to deal with any errors that take place during the execution of programs.
7. Query functions: They provide useful information of API that can be useful in an
application. E.g. Camera parameters or values in the frame buffer.

2.1.2 The OpenGL Interface

GL (Graphics Library): OpenGL function names begin with the letters gl and are stored in
a library usually referred to as GL.

Graphics utility library (GLU): This library uses only GL functions, but contains code for
common objects, such as spheres, that users prefer not to have to write repeatedly. This
library is available in all OpenGL implementations.

GL Utility Toolkit (GLUT): It addresses the problems of interfacing with the window
system. It provides the minimum functionality that should be expected in any modern
windowing system.

Priyanka H V

Page 1

Computer Graphics

Figure below shows the organization of the libraries for an X Window system environment.

2.2. Primitives and Attributes

The basic OpenGL primitives are points in space or vertices.

The sequences of the form to defines objects are


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

The value of type specifies how OpenGL interprets the vertices to define geometric objects.

Other code and OpenGL function calls can occur between glBegin and glEnd.

Attributes can be changed or calculations can be performed for the next Vertex between
glBegin and glEnd, or between two invocations of glVertex.

A major conceptual difference between the basic geometric types is whether or not they have
interiors.

Aside from the point type, all the other basic types will be defined either in terms of vertices
or by finite pieces of lines, called line segments

The primitives and their type specifications include the following:

Line segments (GL_LINES) The line-segment type causes successive pairs of vertices to be
interpreted as the endpoints of individual segments. Because the interpretation is done on a
pair wise basis, successive segments usually are disconnected.

Polylines
(GL_LINE_STRIP) It is used if successive vertices (and line segments) are to be
connected. Many curves can be approximated via a suitable polyline.

GL_LINE_LOOP: If the polyline need to be closed the final vertex is located in the same
place as the first,

GL_LINE_LOOP can be used which will draw a line segment from the final vertex to the
first, thus creating a closed path.

Priyanka H V

Page 2

Computer Graphics

2.2.1. Polygon Basics

Polygon refers to an object that has a border that can be described by a line loop, but has an
interior.

Polygons play a special

role in computer graphics because they

can be displayed rapidly

and they can be used to approximate

curved surfaces.

The performance of graphics systems is measured by the number of polygons per second that
can be displayed.

Ways of displaying polygons:

Only its edges be displayed.

Its interior be filled with a solid color, or a pattern

Either display or not display the edges.

Outer edges of a polygon can be defined easily by an ordered list of vertices. But if the
interior is not well defined, then the polygon may be rendered incorrectly.

Three properties will ensure that a polygon will be displayed correctly: It must be

Simple

Convex and

Flat.

Simple:
A 2-D polygon in which no pair of edges cross each other. They will have
well-defined interiors. Although the locations of the vertices determine
whether or not a polygon is simple, the cost of testing is sufficiently high that
most graphics systems require that the application program do any necessary testing.
Non-simple:
A 2-D polygon in which pair of edges cross each other. Graphics system must
handle by some means if a non-simple polygon is to be displayed and to
define an interior for a non-simple polygon.
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 regardless of the type of the object and its dimension
(whether 2-D or 3-D). Convex objects include triangles, tetrahedra, rectangles, circles, spheres,
and parallelepipeds.

2.2.2. Polygon Types in OpenGL


For objects with interiors the following types can be specified:

Priyanka H V

Page 3

Computer Graphics

Polygons (GL_POLYGON):

Successive vertices define line segments, and a line segment connects the final vertex to the
first. The interior is filled according to the state of the relevant attributes.

In OpenGL, glPolygonMode function can be used to select edges instead of fill (the default).

Triangles and Quadrilaterals (GL_TRIANGLES, GL_QUADS):


These objects are special cases of polygons. Successive groups of three and four vertices are
interpreted as triangles and quadrilaterals, respectively.
Strips and Fans (GLTRIANGLE_STRIP, GL_QUAD_STRIP, GL_TRIANGLE_FAN):
These objects are based on groups of triangles or quadrilaterals that share vertices and edges.

In the triangle strip, each additional vertex is combined with the previous two vertices to define
a new triangle.
For the quad strip, two new vertices are combined with the previous two vertices to define a
new quadrilateral.
A triangle fan is based on 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 (fixed)
point.
2.2.3 Text

In computer graphics text may need to be displayed in a multitude of fashions by controlling


type styles, sizes, colors, and other parameters. Texts provide annotations.

Graphics applications must provide a choice of fonts.

Fonts are families of type faces of a particular style, such as Times, Computer Modern, or
Helvetica.

Two forms of text:


Stroke Text:
Raster text:
Stroke Text:

It is constructed like other graphic primitives.

Vertices are used to define line segments or curves that outline each character.

The characters defined by closed boundaries can be filled.

Advantage:

It can be defined to have all the detail of any other object, and, because it is defined in the
same way as are other graphical objects, it can be manipulated by standard

transformations, and viewed like any other graphical primitive.


If a stroke character is made bigger or rotated, it retains its detail and appearance.
Consequently, a character is needed to be defined only once, and transformations can be
used to generate it at the desired size and orientation.

Defining a full 128- or 256-character stroke font, however, can be complex, and the font can take
up significant memory and processing time.
Priyanka H V

Page 4

Computer Graphics

The standard PostScript fonts are defined by polynomial curves, and they illustrate all the
advantages and disadvantages of stroke text.
Raster text:

It is simple and fast.

Characters are defined as rectangles of bits called bit blocks.

Each block defines a single character by the pattern of 0 and 1 bits in the
block.

A raster character can be placed in the frame buffer rapidly by a bit-blocktransfer (bitblt) operation, which moves the block of bits using a single
instruction.

OpenGL allows the application program to use instructions that allow

direct manipulation of the contents of the frame buffer.

Size of raster characters can be increased only by replicating or duplicating pixels, a process
that gives larger characters a blocky appearance.

Limitations:

Other transformations of raster characters, such as rotation, may not make sense, because
the transformation may move the bits defining the character to locations that do not

correspond to the location of pixels in the frame buffer.


Raster characters often are stored in read-only memory (ROM) in the hardware and
hence, a particular font might be of limited portability.

OpenGL does not have a text primitive, because stroke and bitmap characters can be created
from other primitives. However, GLUT provides a few bitmap and stroke character sets that
are defined in software and are portable. E.g. A bitmap character of 8 x 13 pixels can be
produced by
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, c)

where c is the number of the ASCII character to be placed on the display.


The character is placed at the present raster position on the display, a location that is part of the
graphics state, is measured in pixels, and can be altered by the various forms of the function
glRasterPos*.
2.2.4. Curved Objects
Two approaches to create richer set of objects (means not the primitives) like curved surfaces:

Primitives can be approximated to curves and surfaces.


E.g. A regular polygon of n sides can be approximated to draw a circle.
A regular polyhedron can be approximate to a sphere.
Tessellation: Generally, a mesh of convex polygons can be approximated to a curved
surface either at the rendering stage or within the user program.
Curved objects are defined mathematically and then graphics functions can be built to
implement those objects. Objects such as quadric surfaces and parametric polynomial
curves and surfaces are well understood mathematically, and they can be specified
through sets of vertices.

Priyanka H V

Page 5

Computer Graphics

E.g. A sphere is defined by its center and a point on its surface.


A cubic polynomial curve can be defined by tour points.
2.2.5. Attributes

It is any property that determines how a geometric primitive is to be rendered.


Each geometric type has a set of attributes.

Sl.No Primitive
1
Point
2

Some of the attributes


Color
Size
Line segments
Color,
Thickness, and
Type (solid, dashed, or dotted).
Filled primitives, such as Have more attributes, with enough parameters to specify
polygons
how the fill should be done: E.g.
Not to fill the polygon and to display only its edges
Fill with a solid color or a pattern
Fill with the edges displayed in a color different
from that of the interior
Stroke text (if supported)
Direction of the text string,
Path followed by successive characters in the string
Height and Width of the characters,
Font, and
Style (bold, italic, underlined).

Type of the primitive differs from its attribute.


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

displayed differently.
Attributes may be associated with, or bound to, primitives at various points in the modeling

and rendering pipeline. Bindings may not be permanent.


Immediate-mode graphics: In this, primitives are not stored in the system, but rather are
passed through the system for possible display as soon as they are defined. The present
values of attributes are part of the state of the graphics system. When a primitive is defined,
the present attributes for that type are used, and it is displayed immediately. There is no
memory of the primitive in the system. Only the primitive's image appears on the display;
once erased from the display, it is lost.

2.3. Color
Color in computer graphics is based the three-color theory which says:
If two colors produce the same tristimulus values, then they are visually
indistinguishable. Two colors that match visually are known as metameric pairs; they have
the same tristimulus values.
An additive color model is used because it is more appropriate for CRT displays with the
primaries red, green, and blue. This model considers a color, as being formed from three primary
colors that are mixed to form the desired color. All colors can not be matched in this way. But
with a particular set of primaries say standard red, green, and blue, combined a color, close to the
desired one can be obtained.
The matching process can be represented abstractly as follows.
Matching Color i.e., C = T1R + T2G + T3B,
Priyanka H V

Page 6

Computer Graphics

were R, G, and B represent the three primaries Red, Green and Blue respectively.
T1, T2, T3 are the strengths, or intensities, of the three primaries, called the tristimulus values.
Thus relative to the particular set of primaries, the target color can be characterized by the triplet
(T1, T2, T3). Thus a continuous function is reduced to three numbers. Hence for a visual match,
only a color's tristimulus values are to be matched.
Subtractive color model : It suits for processes such as commercial printing and painting. The
primaries are usually the complementary colors: cyan, magenta, and yellow (CMY). RGB
additive system has a dual with a CMY subtractive system.
Color Gamut: The range of colors that can be produced on a given system with a given set of
primaries.
Color Cube:
In additive color model, a color is viewed as a point in a color solid, as shown below.

The solid is drawn using a coordinate system


corresponding to the three primaries. The distance
along a coordinate axis represents the amount of the

corresponding primary in the color.


The maximum value of each primary is normalized to
1 and hence any color can be represented with this set

of primaries as a point in a unit cube.


The vertices of the cube correspond to black (no

primaries on); red, green, and blue (one primary fully on); the pairs of primaries, cyan
(green and blue fully on), magenta (red and blue fully on), and yellow (red and green
fully on); and white (all primaries fully on). The principal diagonal of the cube connects
the origin (black) with white. All colors along this line have equal tristimulus values and

appear as shades of gray.


With additive color, primaries add light to an initially black display, yielding the desired
color.

Color handling in a graphics system from the programmer's perspective - i.e. , through the
API.:
There are two different approaches.
2.3.1 RGB Color Model
In a three-primary-color, additive-color RGB system, there are conceptually separate frame
buffers for red, green, and blue images.
Each pixel has separate red, green, and blue components that correspond to locations in
memory.

In a typical system, there might be a 1280 x 1024


array of pixels, and each pixel might consist of 24 bits
(3 bytes): 1 byte for each of red, green, and blue. Such
a frame buffer would have over 3 megabytes (MB) of

memory that would have to be redisplayed at video rates.

Priyanka H V

Page 7

Computer Graphics

Programmers specify color components as numbers (using the color cube) between 0.0 and
1.0, where 1.0 denotes the maximum value of the corresponding primary, and 0.0 denotes a
zero value of that primary.
Graphic Function:
In OpenGL, to draw in red, the following function call is used:
glColor3f(1.0, 0.0, 0.0);
The execution of this function will set the present drawing color to red. Because the color is part
of the state, draw in red is continued until the color is changed.
The "3f" is used in a manner similar to the glVertex function: It conveys that, a three-color
(RGB) model is used, and that the values of the components are given as floats in C.
If an integer or byte type to specify a color value, the maximum value of the chosen type
corresponds to the primary fully on, and the minimum value corresponds to the primary fully off.
Advantages and Disadvantages:
RGB Model is used in lighting and shading. It is a more difficult model to support in
hardware, due to higher memory requirements, but modern systems support it more easily
now that memory is cheaper. It is also possible for a system to support true color in
software through the API, and to have the hardware use approximate techniques to
implement a display visually close to an RGB-color display.
Many systems have frame buffers that are limited in depth. Consider a frame buffer
having a spatial resolution of l280 x 1024, but each pixel is only 8 bits deep. The 8 bits
can be divided into smaller groups of bits to assign to red, green, and blue. Although this
technique is adequate in a few applications, it usually does not give enough flexibility in
color assignment, and breaking apart individual bytes into small groups of bits can affect
performance.
Four-color (RGBA) system. The fourth color (A) uses what is called the alpha channel, but is
stored in the frame buffer, as are the RGB values; it can be set with four-dimensional versions of
the color functions. (Chapter 9 covers various uses of the alpha channel, such as for creating fog
effects or for combining images). Here, alpha value is just used in the initialization of an
OpenGL program. The alpha value will be treated by OpenGL as an opacity or transparency
value. Transparency and opacity are complements of each other. An opaque object passes no
light through it; a transparent object passes all light. An object can range from fully transparent
to fully opaque.
To clear an area of the screen-a drawing window-in which output is displayed:
It is done

As first step in any program


Whenever a new frame is to be drawn.

The function call


glC1earCo1or(1.0, 1.0, 1.0, 1.0);
defines a four-color clearing color that is white, because the first three components are set to 1.0,
and is opaque, because the alpha component is 1.0. Then the function glC1ear is used to make
the window on the screen solid and white.
2.3.2. Indexed Color Model
Priyanka H V

Page 8

Computer Graphics

Description:

This model is used when pixel-depth is limited.

Colors can be selected by interpreting the limited-depth pixels as indices, rather than as color
values.

These indices correspond to lines or entries in a table. Suppose that the frame buffer has k
bits per pixel.

Each pixel value or index is an integer between 0 and 2k - 1.

Suppose that the colors can be displayed with an accuracy of m bits; that is, it is possible to
chose from 2m reds, 2m greens, and 2m blues. Hence, any of 23m colors can be produced on the
display, but the frame buffer can specify only 2k of them.

The specification is handled through a user-defined color-lookup table of size 2k x 3m.


The user program fills the 2k entries (rows) of the table with
the desired colors, using m bits for each of red, green, and
blue.
After filling the look-up table,
user can then specify a color by
its index, which points to the appropriate entry in the colorlookup table.
For k =m = 8, a common configuration, user can
choose 256 out of 16 M colors. The 256 entries in the
table constitute the user's color palette.
Graphics Functions:

In color-index mode, the present color is selected by a function such as


glIndex1(element);

that selects a particular color out of the table. Setting and changing the entries in the color-lookup
table involves interacting with the window system.

GLUT allows to set the entries in a color table for each window through the function
glutSetColor(int color, GLfloat red, GLfloat blue, GLfloat green)

Advantages and Disadvantages:


This model is used when pixel-depth is limited.
It requires less memory for the frame buffer and fewer other hardware components.
However, the cost issue is less important now, and color-index mode presents a few
problems. For a standard 8-bit (256-color) frame buffer, a limited set of colors exist to
represent a single image adequately. However, when working with dynamic images that
must be shaded, more colors are usually needed.
2.3.3. Setting of Color Attributes using RGB color model:
3 attributes of the colors:
1. Clear color, which is set to white by the function call
glClearColor(l.0, 1.0, 1.0, 1.0);

Priyanka H V

Page 9

Computer Graphics

2. Rendering color for the points by setting the color state variable to red through the
function call
glColor3f(1.0, 0.0, 0.0);
3. Size of rendered points: For 2 pixels wide, following call is used.
glPointSize(2.0);
2.4. Viewing

A fundamental concept that emerges from the synthetic-camera model is that, the
specification of the objects in the scene is completely independent of the specification of the
camera. Once both the scene and the camera have been specified, the computer system forms

an image by carrying out a sequence of operations in its viewing pipeline.


The application program needs to worry about only specification of the parameters for the

objects and the camera.


There are default viewing conditions (like lens adjustment in camera) in computer image
formation.

2.4.1. 2-D viewing: is based on taking a rectangular area of 2-D world and transferring its
contents to the display.

The area of the world of which the image is to be taken


is known as the viewing rectangle or clipping rectangle.
Objects inside the rectangle are in the image.

Objects outside are clipped out and are not displayed.

Objects that straddle the edges of the rectangle are

partially visible in the image.

The size of the window on the display, and where this window is placed on the display, is
independent decisions.

2-D graphics view is a special case of 3-D graphics. Hence the viewing rectangle is in the
plane z = 0 within 3-D viewing volume:
If viewing volume is not specified, OpenGL uses its
default, a 2 x 2 x 2 cube, with the origin in the center. In
terms of 2-D plane, the bottom-left corner is at
(-1.0, -1.0), and the upper-right corner is at (1.0, 1.0).

2.4.2. The Orthographic View

It is a special case of the orthographic projection.

Orthographic projection

This simple orthographic projection takes a point (x, y, z) and projects it into the point (x, y,
0), as shown below:

2-D world consists of only the plane z = 0.

In OpenGL, an orthographic projection with a right-parallel-piped


viewing volume is specified via

Priyanka H V

Page 10

Computer Graphics
void glOrtho(Gldouble left, Gldouble right, Gldouble bottom, Gldouble top, Gldouble near,
GLdouble far)

In OpenGL, the camera starts off at the origin pointing in the negative z direction as below:
The orthographic projection "sees" only those
objects in the volume specified by viewing
volume.

The

orthographic

projection

also

includes objects behind the camera. Thus, as long


as the plane z =0 is located between near and far,
the 2-D dimensional plane will intersect the
viewing volume.
If using a 3-D volume seems strange in a twodimensional application, the function
void gluOrtho2D(GLdoub1e left, GLdouble right, GLdouble bottom, GLdouble top)
in the utility library may make the program more consistent with its 2-D structure. This function
is equivalent to glOrtho with near and far set to -1.0 and 1.0, respectively.
2.4.3. Matrix Modes

Pipeline graphics systems have an architecture that depends on multiplying together, or


concatenating, a number of transformation matrices to achieve the desired image of a
primitive.

The values of these matrices are part of the state of the system and remain in effect until
changed.

The two most important matrices are


Model-view and
Projection matrices.

At any time, the state includes values for both of these matrices, which start off set to identity
matrices.

The usual sequence is to modify the initial identity matrix, by applying a sequence of
transformations.

There is only a single set of functions that can be applied to any type of matrix.

Matrix mode:
Setting the matrix mode selects the matrix to which the operations apply. It is a variable that is
set to one type of matrix and is also part of the state. The default matrix mode is to have
operations apply to the model-view matrix. So to alter the projection matrix, modes must be
switched.

The following sequence is common for setting a 2-D viewing rectangle:


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

This sequence defines a 500 x 500 viewing rectangle with the lower-left corner of the rectangle
at the origin of the 2-D system. It then switches the matrix mode back to model-view mode. In
Priyanka H V

Page 11

Computer Graphics

complex programs, it is always better to return to a given matrix mode, to avoid possible
confusion over the current mode. E.g. In this case mode returned to model-view mode.
2.5. Control Functions

The OpenGL Utility Toolkit (GLUT) is a library of functions that provides a simple interface
between the systems.

The application programs written using GLUT run under multiple window systems.

2.5.1. Interaction with the Window System


The term window is used in a number of different ways in the graphics and workstation
literature.
Window or screen window denotes a rectangular area of our display that, by default, is
the screen of a raster CRT. It has a height and width. It displays the contents of the frame
buffer. So, positions in the window are measured in window or screen coordinates, where
the units are pixels.
In a modern environment, many windows can be displayed on the CRT screen. Each can
have a different purpose, ranging from editing a file to monitoring the system. The term
window system refers to the multi-window environment provided by systems such as the
X Window system and Microsoft Windows.
The window in which the graphics output appears is one of the windows managed by the
window system. Hence, to the window system, the graphics window is a particular type
of window-one in which graphics can be displayed or rendered. References to positions
in this window are relative to one corner of the window. While deciding which corner is
the origin, much care must be taken.
Usually, the lower-left corner is the origin, and has window coordinates (0, 0). However,
virtually all raster systems display their screens from top to bottom, left to right. From
this perspective, the top-left corner should be the origin.
OpenGL commands assume that the origin is bottom-left. But information returned from
the windowing system, such as the mouse position, often has the origin at the top left and
thus requires conversion of the position from one coordinate system to the other.
Graphics GLUT functions:
1. glutInit(int *argcp, char **argv)

It initiates an interaction between the windowing system and OpenGL. It is used before
opening a window in the program.

The two arguments allow the user to pass command-line arguments, as in the standard C
main function, and are usually the same as in main.

2. glutCreateWindow(char *tit1e)

It opens an OpenGL window.

title string provides title at the top to the window displayed.

The window thus created has a default size, a position on the screen, and characteristics such
as use of RGB color. But GLUT functions are also available to specify these parameters
before to the window creation.

E.g. The code


glutInitDisp1ayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
Priyanka H V

Page 12

Computer Graphics

glutIn1tW1ndowSize(480, 640);
glutInitWindowPosition(0, 0);
specifies a 480 x 640 window in the top-left corner of the display.

RGB is specified rather than indexed (GLUT_INDEX)color.

A depth buffer for hidden-surface removal.

And double rather than single (GLUT_SINGLE) buffering.

2.5.2. Aspect Ratio and Viewports

The aspect ratio of a rectangle is the ratio of the rectangle's width to its height.

The independence of the object, viewing, and workstation window specifications can cause
undesirable side effects if the aspect ratio of the viewing rectangle, specified by glOrtho, is
not the same as the aspect ratio of the window specified by glutInitWindowSize.

Figure illustrates the difference.


(a) Viewing Rectangle (b) Display window
If they differ objects are distorted on the screen. This
distortion is a consequence of the default mode of
operation, in which the entire clipping rectangle is
mapped to the display window.

This distortion can be avoided in two ways:

By ensuring that the clipping rectangle and display window have the same aspect ratio.
Using the concept of a viewport: It is the flexible way.

A viewport is a rectangular area of the display window. By default, it is the entire window,
but it can be set to any smaller size in pixels via the function
void glViewport(GLint x, GLint y, GLsizei w, GLsizei h)

where (x. y) is the lower-left corner of the viewport (measured relative to the lower-left corner of
the window), and w and h give the height and width, respectively.

The types are all integers specifying positions and distances in pixels.

Primitives are displayed in the viewport, as


shown in figure.

For a given window, height and width of the


viewport can be adjusted to match the aspect ratio
of the clipping rectangle, thus preventing any
object distortion in the image.

The viewport is part of the state. Hence changing the viewport between successive
rendering/redisplay gives the effect of multiple viewports with different images in different
parts of the window.

2.5.3. Main, display, and myinit Functions

Priyanka H V

Page 13

Computer Graphics

The screen may clear immediately before the output primitive is seen. Solution to this problem
includes:
Inserting a delay, such as via a standard function such as sleep(enoughtime).
By event-processing:say using the GLUT function
void glutMainLoop(void)
which causes the program to begin an event-processing loop.
If there are no events to process, the program will sit in a wait state, with the graphics
on the screen, until the program is terminated through some external means, such as
by hitting the "kill" key.

Display callback A function which sends Graphics to the screen. It is specified through the
GLUT function
void glutDisplayFunc(void (*func)(void))

Here, func is the name of the function that will be called whenever the windowing system
determines that the OpenGL window needs to be redisplayed.
One of these times include:

when the window is first opened. Thus if all graphics are put into this function (for our
non-interactive example), func will be executed once and the graphics (say gasket) will

be drawn.
when the window is moved from one location on the screen to another and
when a window in front of the OpenGL window is destroyed, making visible the whole
OpenGL window.

A main program that works for most non-interactive applications:


#include <GL/glut.h>
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(500, 500);
glutInitWindowPosition(0,0); .
glutCreateWindow("simple OpenGL example)
glutDisplayFunc(display);
myinit( );
glutMainLoop();
}

myinit( ) sets the OpenGL state variables dealing with viewing and attributes. These
parameters are preferred to set once, independently of the display function.

2.5.4. Program Structure

Every program further written will have the same structure as the gasket program.

Always the GLUT toolkit is used.


The main function will then consist of calls to GLUT functions to set up our window(s)
and to make sure that the local environment supports the required display properties.

Priyanka H V

Page 14

Computer Graphics

The main will also name the required callbacks and callback functions. Every program

must have a display callback, and most will have other callbacks to set up interaction.
The myinit function will set up programmers options, usually through OpenGL functions
on the GL and GLU libraries. Although these options could be set in main, it is probably
clearer to keep GLUT functions separate from OpenGL functions. Most of the graphics
output will be generated in the display callback, in most programs.

2.6. The Gasket Program


NOTE:program refer class notes
2.7. Polygons and Recursion
If the program is run with more iteration, then much of the randomness in the image would
disappear. Then there will be there are no points in the middle regardless of how many points are
generated.
Another method of generating the Sierpinski gasket that uses polygons instead of points,
and does not require the use of a random-number generator.
If line segments connecting the midpoints of the sides of the original triangle are drawn, then the
original triangle would be divided into four triangles, the middle one containing no points.
Same observation (i.e., subdivide each of these triangles into four
triangles by connecting the midpoints of the sides, and each middle
triangle will contain no points) is applicable to each of the other three
triangles.
Advantage:
Use of polygons enables filling of solid areas on the display.
Strategy:
Strategy starts with a single triangle and subdivides it into four smaller triangles by bisecting the
sides, and then removes the middle triangle from further consideration. This procedure is
repeated on the remaining triangles until the size of the triangles that is removed is small enoughabout the size of one pixel - that the remaining triangles can be drawn.
NOTE: Program refer class notes
2.8. Three-Dimension Gasket
2-D graphics is a special case of 3-D graphics. It is illustrated by converting 2-D Sierpinski
gasket program to a program that will generate a 3-D gasket.
Either of the two approaches that used for the 2-D can be used. Both
extensions start in a similar manner, replacing the initial triangle with a
tetrahedron.
NOTE: Program refer class note.
Use of Polygons in Three Dimensions

Following the second approach, faces of a tetrahedron are the four triangles determined

by its four vertices.


Then the subdivision algorithm can be applied to each of the triangle faces. Thus, the
code is almost the same as in 2-D.

Priyanka H V

Page 15

Computer Graphics

triangle routine now uses points in 3-D, rather than in 2-D:

2.8.1. Hidden-Surface Removal:


If 3-D Sierpinski gasket is constructed out of small solid tetrahedra, then only those faces of
tetrahedra that are in front of all other faces as seen by a viewer can be seen. Hence the above
order is contrast to this.

Figure shows a simplified version of this hidden-surface problem.

From the viewer's position, only the triangle A is seen clearly, but
triangle B is blocked from the view, and triangle C is only partially
visible.

If the position of the viewer and the triangles are known, then the triangles must be drawn to
get the correct image.

Algorithms for ordering objects so that they are drawn correctly are called visible-surface
algorithms or hidden-surface-removal algorithms, depending on problem under
consideration.

z-buffer algorithm:

It is a hidden-surface-removal algorithm that is supported by OpenGL. This algorithm

can be turned on (enabled) and off (disabled) easily.


In the main program, auxiliary storage is requested for a z or depth buffer, by modifying
the initialization of the display mode to the following:
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);

Algorithm is enabled by the function call


glEnable(GL_DEPTH_TEST)
either in main.c or in an initialization function such as myinit.c.

Because the algorithm stores information in the depth buffer, this buffer must be cleared
whenever the display is to be redrawn. Thus, clear procedure in the display function is
modified as follows:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

Priyanka H V

Page 16

You might also like