0% found this document useful (0 votes)
174 views109 pages

Unit 1 PDF

The document discusses computer graphics and the OpenGL library. It provides definitions and explanations of key concepts in computer graphics like pixels, computer graphics applications, graphics system components, CRTs, and graphics architectures. It then describes OpenGL, including its functions, related libraries, basic syntax, and how to set up a basic display window and program using GLUT functions. The complete program structure initializes GLUT, creates a window, specifies a display callback, sets display options and background color, and enters the main loop.

Uploaded by

rajath bhat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
174 views109 pages

Unit 1 PDF

The document discusses computer graphics and the OpenGL library. It provides definitions and explanations of key concepts in computer graphics like pixels, computer graphics applications, graphics system components, CRTs, and graphics architectures. It then describes OpenGL, including its functions, related libraries, basic syntax, and how to set up a basic display window and program using GLUT functions. The complete program structure initializes GLUT, creates a window, specifies a display callback, sets display options and background color, and enters the main loop.

Uploaded by

rajath bhat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

Computer Graphics

Computer Graphics is the pictorial


representation of information using a computer
program. In Computer Graphics, pictures as
graphical subjects are represented as a collection
of discrete picture element called pixels. Pixel is
smallest addressable screen element.
•William Fetter coined term “computer graphics”
in 1960 to describe new design methods .
Computer Graphics Applications
•Display of Information
•Design
•Simulation and Animation
•User Interface
Major components of a Graphics system:
•Input Devices
•Processor
•Memory
•Frame Buffer
•Output devices
Cathode Ray Tube[CRT]

Two types of CRT


•Random scan CRT[image oriented approach]
•Raster scan CRT[Object oriented approach]
Different Graphics Architectures
•Early Graphics Architecture

•Display Processor Architecture


•Pipeline Architecture
Introduction to OpenGL[Open Graphics Library]

•A basic library of functions is provided in OpenGL for specifying graphics


primitives , attributes, geometric transformation , viewing transformation and
many other operations.
•OpenGL is an application program interface that is used to define 2D and 3D
computer graphics.
• The interface consists of over 250 different function calls which can be used
to draw complex three-dimensional scenes from primitives . OpenGL was
developed by silicon Graphics Inc. (SGI) in 1992 and is widely used in CAD,
Virtual reality, scientific visualization, information visualization and flight
simulation.
•OpenGL’s basic operation is to accept primitives such as points, lines and
polygons, and convert them into pixels. This is done by a graphics pipeline .
Basic OpenGL Syntax

•OpenGL basic library are prefixed with gl, and each component word within a
function name has its first letter capitalized.
ex:glBegin, glClear, glCopyPixels, glPolygonMode etc…

•Certain functions require that one or more arguments be displayed a symbolic


constant specifying , for instance , a parameter name , a value for a parameter,
or a particular mode.

•All such constants begin with the Uppercase letters GL.In addition ,
component words within a constant name are written in capital letters,and the
underscore(_) is used as a separator between all component words in the name.
ex: GL_2D,GL_RGB,GL_COLOR_BUFFER_BIT etc…
•OpenGL uses special built-in, data-type names,
each data type name begins with the capital
letters GL, and the remainder of the name is a
standard data type designation written in
lowercase letters.
ex:GLbyte, GLshort, GLfloat, GLdouble etc..
Related Libraries
•The OpenGL basic library, there are a number of associated
libraries for handling special operations.
•The OpenGL Utility(GLU) provides routines for setting up
viewing and projection matrices, describing complex objects with
line and polygon approximation, displaying quadrics and B-
splines using linear approximation, processing the surface-
rendering operations, and other complex tasks.
•GLU function name start with the prefix glu. There is also an
object-oriented toolkit based on OpenGL called Open Inventor,
which provides routines and predfined object shapes for
interactive three-dimensional applications.This toolkit is written
in C++.
There are several window –system libraries that support OpenGL functions
for a variety of machines.
•The OpenGL Extension to the X Window System(GLX) provides a set of
routines that are prefixed with the letters glx.
•Apple systems can use the Apple GL(AGL) interface for window-
management operations. Function names for this library are prefixed with agl.
•Microsoft windows systems, the WGL routines provide a Windows-to-
OpenGL inetrface.These routines are prefixed with the letters wgl.
•The Presentation Manager to OpenGL(PGL) is an interface for the IBM
OS/2, which uses the prefix pgl for the library routines.
•The OpenGL Utility Toolkit(GLUT) provides a library fo functions are
prefixed with glut, and this library also contains methods for describing and
rendering quadric curves and surfaces.
•Its main objective is to connect the graphics package with the corresponding
OS.
Note : To create a graphics display using OpenGL we first need to set up a
display window on our video screen. This is simply the rectangular area of the
screen in which our picture will be displayed.
Library Organization of Open GL
Header Files
•The Header file for the window system.For
instance, with Microsoft windows, the header files
that accesses the WGL routines is windows.h.
•This header file must be listed before the OpenGL
and GLU header files because it contains macros
needed by the Microsoft Windows version of the
OpenGL libraries. So the source file begin with
#include<windows.h>
#include<GL/gl.h>
#include<GL/glu.h>
Continued…..
•GLUT to handle the window-managing operations, we do not need
to include gl.h and glu.h because GLUT ensures that these will be
included correctly so we can replace the header files for OpenGL
and GLU with
#include<GL/glut.h>
•On some systems ,the header files for OpenGL and GLUT routines
are found in different places in the file system.First instance , on
Apple OS x systems, the header file inclusion statement as follows
#include<GLUT/glut.h>
•In addition , we will need to include header files that are required
by the c++ code.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
Display-Window management using GLUT
Control functions supported by Open GL:
•Consider a simplified, minimal number of operations for displaying
a picture. The OpenGL Utility Toolkit first step is to initialize GLUT.
glutInit (&argc,argv);
Syntax : glutInit(int *argc, char **argv);
• The 2 arguments enables the programmer to pass command line
arguments.

•Next, Display window is to created on the screen with a given


caption for the title bar.
glutCreateWindow (“An Example OpenGL program”);
Syntax:- glutCreateWindow(char *name);
where ->name :- ASCII character string for use as window name.
•Then we need to specify what the display window is to contain.
To ,that we create a picture using OpenGL functions and pass the
picture definition to the GLUT routine glutDisplayFunc, which
assigns our picture to the display window. Suppose, we have the
OpenGL code for describing a line segment in a procedure called
lineSegment

glutDisplayFunc (lineSegment);
Syntax: glutDisplayFunc(void (*func)(void));

•glutDisplayFunc(): The procedure lineSegment that we set up to


describe our picture is referred to as a display callback function.
This procedure is described as being “registered” by as the
routine to invoke whenever the display window might need to be
redisplayed.
Note: OpenGL programs are organized as set of callback
functions that are to be invoked when certain actions occur.
•We need one more GLUT function to complete the window
processing operations. This function must be the last one in our
program. It displays the initial graphics and puts the program into
an infinite loop that checks for input from devices such as a
mouse or keyboard.

glutMainLoop();
Syntax:glutMainLoop(void);

•This function cause the program to begin an event processing


loop. If there are no events to process, then the program would
enter the wait state with the output on the screen freezed. It is
similar to the getch() function of C langauge.
•Display window that we created will be in some default location and size, we
can set these parameters using addition GLUT function. We use the
glutInitWindowSize ( ) to give an initial location for the upper left corner of
the display window.This position is specified in integer screen
coordinates,whose origin is at the upper-left corner of the screen.

glutInitWindowPosition (50, 100) ;


Syntax:glutInitWindowPosition(int x, int y);
x :- Window X location in pixels.
Y :- Window Y location in pixels.

•One more function is used to set the initial pixel width and height of the
display window. Thus , we specify a display window with an initial width of
400 pixels and a height of 300 pixels as shown in below statement

glutInitWindowSize (400, 300) ;


Syntax:glutInitWindowSize(int width, int height);
width : Width in pixels.
Height:- Height in pixels.
•We can also set a number of other options for the display
window, such as buffering and a choice of color
modes.Arguments for this routine are assigned symbolic GLUT
constants.
• The following command specifies that a single refresh buffer is
to be used for the display window and that we want to use the
color mode which uses red,green, and blue (RGB) components to
select color values.

glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB );


Syntax:glutInitDisplayMode(unsigned int mode);
A Complete OpenGL Program
•For the display window, we can choose a background color. And we need to
construct a procedure that contains the appropriate OpenGL functions for the
picture that we want to display.
•Using RGB color values ,we set the background color for the display window to
be white as follow : glClearColor (1.0, 1.0, 1.0, 0.0 );
•All three of these components were set to the same intermediate value between
0.0 and 1.0, we would get some shade of gray.
• The fourth parameter in the glClearColor function is called the alpha value for
the specified color.One use for the Aplha value is as a “blending” parameter.Alpha
values is used to determine the resulting color for two overlapping objects.
•Alpha value of 0.0 indicates a transparent object,and alpha value indicates an
opaque object.
•To get the assigned window color displayed, we need to invoke the following
OpenGL function
glClear (GL_COLOR_BUFFER_BIT) ;
•The argument of this function is an OpenGL Symbolic constant specifying that it
is the bit values in the color buffer(refresh buffer) that are to be set to the values
indicated in this function.
•We can choose a variety of color schemes for
the objects we want to display in a scene. For
example,we will set the object color to be a dark
green : glColor3f (0.0, 0.4, 0.2) ;
•The suffix 3f on the glColor function indicates
that we are specifying the three RGB color
components using floating-point(f) values.This
function requires that the values be in the range
from 0.0 to 1.0.
•We need to tell OpenGL how we want to “project” our picture onto the
display because generating a two-dimensional picture is treated by OpenGL as
a special case of three-dimensional viewing.
•So, we can set the projection type(mode) and other viewing parameters that
we need with the following functions:

glMatrixMode (Gl_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 150.0 );

•This specifies that an orthogonal projection is to be used to map the contents


of a two-dimensional rectangular area of world coordinates to the screen, and
that the x-coordinate values within this rectangle range from 0.0 to 200.0 with
y-coordinate values ranging from 0.0 to 150.0.
•The GLU function gluOrtho2D defines the coordinate reference frame within
the display window to be (0.0,0.0) at the lower-left corner of the display
window and (200.0,150.0) at the upper-right window corner.
•Finally , call the appropriate OpenGL routines to create our line
segment. The following code defines a two dimensional ,staright-
line segment with integer, Cartesian product coordinates (180,15)
and (10,145).
glBegin (GL_LINES);
glVertex2i (180, 15) ;
glVertex2i (10, 145) ;
glEnd ( ) ;
glFlush ( ) : This routine to force execution of our OpenGL
function, which are stored by computer systems in buffers in
different locations , depending on how OpenGL is implemented.
•The following OpenGL program is organized
into three functions. All initializations and
related One-time parameter settings in function
init.
•Geometric description of the “picture” that we
want to display is in function lineSegment,
which is the function that will be referenced by
the GLUT function glutdisplayFunc.
•The main function contains the GLUT functions
for setting up the display window and getting our
line segment onto the screen.
#include<GL/glut.h>
Void init (void)
{
glClearColor(1.0, 1.0, 1.0, 0.0); //set display-window color to white.
glMatrixMode (GL_PROJECTION); //set projection parameters.
gluOrtho2D (0.0, 200.0, 0.0,150.0);
}

Void lineSegment (void)


{
glClear (GL_COLOR_BUFFER_BIT); //clear display window.
glColor3f (0.0, 0.4, 0.2); //set line segment color to green.
glBegin (GL_LINES);
glVertex2i (180, 15); // specify line segment geometry.
glVertex2i (10, 145);
glEnd ( );
}

Void main (int argc, char** argv)


{
glutInit (&argc, argv); //Initialize GLUT
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); //set display mode.
glutInitWindowPosition ( 50, 100); //set top-left display window position.
glutInitWindowSize (400, 300); //set display-window width and height
glutCreateWindow (“An Example OpenGL Program”); //create display window

init ( ); //Execute initialization procedure.


glutDisplayFunc (lineSegment); //Send graphics to display window.
glutMainLoop ( ); //Display everything and wait.
}
Error Handling in OpenGL
•OpenGL and GLU libraries have a relatively simple method of
recording errors. When OpenGL detects an error in a call to base
library routine or a GLU routine , it records an error code
internally , and the routine which caused the error is ignored.
•OpenGL only records one error code at a time. Once an error
occurs, no other code will be recorded until your program
explicitly queries the OpenGL error state:
Glenum code;
Code = glGetError ( );
•This call returns the current error code and clears the internal
error flag. If the returned value is equal to the OpenGL symbolic
constant GL_NO_ERROR , any other return value indicates that
a problem has occurred.
•To use it, we first retrieve the current error code, and then pass it as
a parameter to this function. The return value can be printed out
using, for ex: the C standard library fprintf function :
#include<stdio.h>
GLenum code;

const GLubyte *string;

Code = glGetError ();


String = gluErrorString (code);
fprintf( stderr, “OpenGL error: %s\n”, string );

•The value returned by gluErrorString points to a string located


inside the GLU library. It is not a dynamically-allocated string, so it
must not be deallocated by our program. It also must not be modified
by our program.
•Easily encapsulation these function calls into a general error-reporting
function in our program. The following function will retrieve the current error
code,print the descriptive error string, and return the code to the calling
routine.

#include<stdio.h>
Glenum errorCheck ( )
{
GLenum code;
const GLubyte *string;

code = glGetError ();


if (code != GL_NO_ERROR)
{
string = gluErrorString (code);
fprintf( stderr, “OpenGL error: %s\n”, string );
}
return code;
}
Graphics Output Primitives
•To describe the structure of the individual objects and their coordinate locations
within the scene. Those functions in a graphics package that we use to describe the
various picture components are called the Graphics Output primitives or simply
primitives.
•The Output primitives describing the geometry of objects are typically referred to
as geometric primitives.
•Point positions and straight-line segments are the simplest geometric primitives.
•Additional geometric primitives that can be available in a graphics package
include circles and other conic sections, quadric surface, spline curves and surfaces,
and polygon color areas.
•Most graphics system provide some functions for displaying character strings.
•After the geometry of a picture has been specified within a selected coordinate
reference frame, the output primitives are projected to a two dimensional plane,
corresponding to the display area of an output device, and scan converted into
integer pixel position within the buffer frame.
Coordinate Reference Frames :
•To describe a picture, first decide upon a convenient
cartesian coordinate system, called the world-coordinate
reference frame.
•These coordinate positions are stored in the scene
description along with other information about the objects,
such as their color and their coordinate extent which are the
minimum and maximum x,y and z values for each object. A
set of coordinates is also described as a bounding box for
an object.
•For a two dimensional figure, the coordinate extents are
sometimes called an object’s bounding rectangle.
Screen Coordinates :
•Location on a video monitor are referenced in integer screen
coordinates,which correspond to the pixel positions in the frame
buffer.Pixel coordinate values give the scan line number(the y
value) and the column number(the x value along a scan line).
ex: An integer range for screen positions with the coordinate
origin at the lower-left of a screen area as shown in figure or use
noninteger Cartesian values for a picture description.
•Scan-line algorithms for the graphics primitives use the defining
coordinate descriptions to determine the locations of pixels that
are to be displayed.
y

5
4
3
2
1
0
0 1 2 3 4 5 x
Pixel positions referenced with respect to
the lower-left corner of a screen area.
•Once pixel positions have been identified for an
object , the appropriate color values must be
stored in the buffer.
setPixel(x,y);
•This procedure stores the current color setting
into the frame buffer at integer
position(x,y),relative to the selected position of
the screen-coordinate origin.To retrieve the
current frame-buffer setting for a pixel location
with color using following function:
getPixel(x,y,color);
•In this function , parameter color receives an
integer value corresponding to the combined
•Absolute Coordinate Specification
This means that the values specified are the actual positions
within the coordinate system in use.
•Relative Coordinate Specification
Some graphics package also allow positions to be specified using
relative coordinates. This method is useful for various graphics
applications, such as producing drawings with pen plotters, artist’s
drawing and painting systems, and graphics packages for
publishing and printing applications. Specify a coordinate position
as an offset from the last position that was referenced is called
current position.
Specifying a Two –Dimensional World-Coordinate Reference
Frame in OpenGL :
•The gluOrtho2D command is a function use to set up any two
dimensional Cartesian reference frame.The arguments for this
function are the four values defining the x and y coordinate limits
for the picture to display.
•The gluOrtho2D function specifies an orthogonal projection,by
specifyning the coordinate values are placed in the identify matrix as
the projection matrix.
•Assign the identity matrix as the projection matrix before defining
the world-coordinate range.
glMatrixMode(GL_PROJECTION);
glLoadIdentity( );
gluOrtho2D(xmin,xmax,ymin,ymax);
•The display window referenced by coordinates(xmin,ymin) at
the lower-left corner and by coordinates(xmax,ymax) at the
upper-left corner as shown in figure.
•The geometric describing a picture, all positions for the openGL
primitives must be given in absolute coordinates,with respect to
the reference frame defined in the gluOrtho2D function.

Video Screen

ymax
Display
Window

ymin

xmin
xmax
OpenGL Geometric Primitives

GL_LINES
GL_POLYGON
GL_LINE_STRIP GL_LINE_LOOP
GL_POINTS

GL_TRIANGLES

GL_QUADS
GL_QUAD_STRIP
GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
OpenGL Point Functions
•To specify the geometry of a point, give a coordinate
position in the world reference frame.
•OpenGL function to state the coordinate values for a
single position:
glVertex*( );
•Where-> the asterisk(*) indicates that suffix codes are
required for this function.These suffix codes are used to
identify the spatial dimension ,the numerical data type to
be used for the coordinate values,and a possible vector
form for the coordinate specification.
•This single function is used for point,line and polygon
specification.
•glVertex functions must be placed between a glBegin( ) and
glEnd( ) as shown below syntax:

glBegin(GL_POINTS);
glVertex*( );
glEnd( );

•The argument of the glBegin function is used to identify the


kind of output primitive that is to be displayed and glEnd ( ) takes
no arguments.
ex: For point plotting , the argument of the glBegin function is
the symbolic constant GL_POINTS.
ex:Three equally spaced points are plotted
along a 2D,straight-line path with a slope of
2,coordinates are given as integer pairs.

glBegin(GL_POINTS);
glVertex2i (50,100);
glVertex2i(75,150);
glVertex2i(100,200); y
glEnd( );

•Alternatively,specify the coordinates values


for the preceding point in array such as: 200
int point1[ ] = {50,100};
int point2 [ ] ={75,150}; 150

int point3[ ]= {100,200}; 100

•And call the OpenGL functions for plotting 50

the three points as:


50 100 150 x
glBegin(GL_POINTS);
glVertex2iv(point1); Display of three point positions
glVertex2iv(point2); generated with glBegin(GL_POINTS)
glVertex2iv(point3);
glEnd( );
OpenGL Line Functions
glBegin(GL_LINES);
p3

glVertex2iv(p1); p1

glVertex2iv(p2);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5); p4
p2
glEnd( );
glBegin(GL_LINE_STRIP); p3

glVertex2iv(p1);
glVertex2iv(p2); p5
p1

glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
p4
p2
glEnd( );
glBegin(GL_LINE_LOOP);
glVertex2iv(p1); p3

glVertex2iv(p2);
p5 p1
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glEnd( ); p2
p4
glBegin(GL_POINTS);
glVertex3f(-78.05,909.72,14.60);
glVertex3f(261.91,-5200.67,188.33);
glEnd( );
Class wcPtd2D {
public:
Glfloat x,y;
};
wcPt2D pointPos;
pointPos.x = 120.75;
pointPos.y = 45.30;
glBegin(GL_POINTS);
glVertex2f(pointPos.x,pointPos.y);
glEnd();
Line Drawing Algorithms
•A straight-line segment in a scene is defined by
the coordinate positions for the endpoints of the
segment.
•To display the line on a raster monitor, the
graphics first project the endpoints to integer
screen coordinates and determine the nearest
pixel positions along the line path between the
two endpoints.
•Horizontal and vertical lines to be displayed
with a stair-step appearance(known as “the
jaggies”).
DDA[Digital Differential Analyzer] Algorithm
Step-1 :-Get the input of two end points(x0,y0) and (x1,y1)
Step-2:-Calculate the difference between two end points.
dx=x1-x0
dy=y1-y0
Step-3:-Based on the calculated difference in step-2,to identify the number of steps to put
pixel. If dx>dy, then we need more steps in x coordinate, otherwise in y-coordinate
if(dx>dy)
steps=absolute(dx);
else
steps=absolute(dy);
Step-4:-Calculate the increment in x-coordinate and y-coordinate
xincrement=dx/(float) steps;
yincrement=dy/(float) steps;
Step-5:Put the pixel by successfully incrementing x and y coordinates accordingly and complete the drawing of the line
for (int v=o; v<steps; v++)
{
x=x+xincrement;
y=y+yincrement;
putPixel(x,y);
}
Bresenham’s Line Algorithm
•An accurate and efficient raster line-generating algorithm, developed by
Bresenham.
•To determine at the next sample position whether to plot the pixel at
position(11,11) or the one at (11,12).
•To illustrate Bresenham’s approach, first consider the scan-conversion process for
lines with positive slope less than 1.0.
•Starting from the left endpoint(x0,y0) of a given line , determined that the pixel at
(xk,yk) and to decide which pixel to plot in column xk+1=xk+1 choices are the pixels at positions(xk+1,yk) and
(xk+1,yk+1).

yk+3 y = mx+b

yk+2
yk+1
yk
xk xk+1 xk+2 xk+3 x
•At pixel position xk+1,label vertical pixel separations from the line path as dlower and dupper.The y coordinate on the line at
pixel column position xk+1 is calculated as
y
y=m(xk+1)+b
then
yk+1
dlower=y-yk dupper
yk+1-yk =m(xk+1)+b-yk
and yk dlower
dupper=(yk+1)-y
xk+1
x
=yk+1-m(xk+1)-b
•To determine which of the two pixels is closest to the line path, set up an efficient test that is based on the difference between the two
pixel separations as follows:
dlower-dupper=2m(xk+1)-2yk+2b-1

•A decision parameter pk for the kth step in the line algorithm by substituting m=∆y/∆x
Where: ∆y and ∆x are the vertical and horizontal separations of the endpoint positions, and defining the decision parameter as
pk= ∆x(dlower-dupper)
=2∆y.xk-2∆x.yk+c

Where: Parameter c is constant,which is independent of the pixel position and will be eliminated in the recursive calculations for pk.
•If the pixel at yk is “closer” to the line path than the pixel at yk+1(that is dlower<dupper),then decision parameter pk is negative. In that
case plot the lower pixel; otherwise, plot the upper pixel.
•Coordinate changes along the line occur in unit steps in
either the x or y direction. At step k+1, the decision
parameter is evaluated as follows:
pk+1=2∆y.xk+1-2∆x.yk+1+c
Subtracting from pk+1 to pk
pk+1-pk=2∆y(xk+1-xk)-2∆x(yk+1-yk)+c

However, xk+1=xk+1, so that


pk+1=pk+2∆y-2∆x(yk+1-yk)+c
Where the term yk+1-yk is either 0 or 1.
•The first parameter p0 is starting pixel position(x0,y0) and with m evaluated as ∆y/∆x
follows
p0=2∆y-∆x
Bresenham’s Line-Drawing Algorithm for |m| < 1.0
Step-1:Input the two line endpoints and store the left
endpoint in (x0,y0).
Step-2:set the color for frame buffer position (x0,y0);that is , plot the first point.
Step-3:calculate the constants ∆x, ∆y,2∆y,and 2∆y-2 ∆x, and obtain the starting value for
the decision parameter as
p0=2∆y- ∆x
Step-4:At each xk along the line, starting at k=0,perform the following test:
If pk<0,the next point to plot is (xk+1,yk) and
pk+1=pk+2∆y
Otherwise,the next point to plot is (xk+1,yk+1) and
pk+1=pk+2∆y-2∆x
Step-5:Repaeat step-4 ∆x-1 more times.
Circle-Generating Algorithm
circle drawing algorithm more efficient is that circles centred at (0, 0) have eight-
way symmetry. Similarly to the case with lines,there is an incremental algorithm
for drawing circles –the mid-point circle algorithm. In the mid-point circle
algorithm, we use eight-way symmetry so only ever calculate the points for the top
right eighth of a circle, and then use symmetry to get the rest of the points
Midpoint Circle Algorithm

Step-1:Input radius r and circle center(xc , yc), then set the coordinates for the first point on the
circumference of a circle centered on the origin as
(x0,y0)=(0,r)
Step-2:calculate the initial value of the decision parameter as
p0=5/4-r
Step-3:At each xk position , starting at k=0, perform the following test:
If pk<0, the next point along the circle centered on (0,0) is (xk+1,yk) and
pk+1=pk+2xk+1+1
Otherwise, the next point along the circle is (xk+1,yk-1) and
pk+1=pk+2xk+1+1-2yk+1
where 2xk+1=2xk+2 and 2yk+1=2yk-2
Step-4:Determine symmetry points in the other seven octants.
Step-5:Move each calculated pixel position (x , y) onto the circular path centered at (xc , yc) and plot the coordinate values as
follows:
x=x + xc
y=y + yc
Step-6:Repeat steps-3 through 5 until x ≥ y
Ellipse-Generating Algorithms
Ellipse – A modified circle whose radius varies from a
maximum value in one direction (major axis) to a minimum
value in the perpendicular direction (minor axis).

d1
F1 P=(x,y)
d2
F2

The sum of the two distances d1 and d2, between the fixed positions F1 and F2 (called the foci of the
ellipse) to any point P on the ellipse, is the same value, i.e.
d1 + d2 = constant
•Symmetry between quadrants
•Not symmetric between the two octants of a quadrant
•Thus, we must calculate pixel positions along the elliptical
arc
through one quadrant and then we obtain positions in the
remaining
3 quadrants by symmetry
(-x, y) (x, y)
ry

rx

(-x, -y) (x, -y)


Decision parameter:

Slope = -1
1
ry 2

rx
Slope = -1
1
ry 2
rx

Starting at (0, ry) we take unit steps in the x direction until we


reach the boundary between region 1 and region 2. Then we
take unit steps in the y direction over the remainder of the curve
in the first quadrant.
At the boundary

therefore, we move out of region 1 whenever


Midpoint Ellipse Algorithm

Midpoint
yi 
yi-1

xi xi + xi +
1 2
Assuming that we have just plotted the pixels at (xi , yi).
The next position is determined by:

If p1i < 0 the midpoint is inside the ellipse  yi is closer


If p1i ≥ 0 the midpoint is outside the ellipse  yi – 1 is closer
Decision Parameter (Region 1)

At the next position [xi+1 + 1 = xi + 2]

OR

where yi+1 = yi
or yi+1 = yi – 1
Decision Parameter (Region 1)
Decision parameters are incremented by:

Use only addition and subtraction by obtaining

At initial position (0, ry)


Region 2
Over region 2, step in the negative y direction and midpoint is taken
between horizontal pixels at each step.

Midpoint
yi 
yi-1

xi xi + xi +
1 2
Decision parameter:

If p2i > 0 the midpoint is outside the ellipse  xi is closer


If p2i ≤ 0 the midpoint is inside the ellipse  xi + 1 is closer
Decision Parameter (Region 2)

At the next position [yi+1 – 1 = yi – 2]

OR

where xi+1 = xi
or xi+1 = xi + 1
Decision Parameter (Region 2)
Decision parameters are incremented by:

At initial position (x0, y0) is taken at the last position


selected in region 1
Midpoint Ellipse Algorithm
1.Input rx, ry, and ellipse center (xc, yc), and obtain the first point on an
ellipse centered on the origin as
(x0, y0) = (0, ry)
1.Calculate the initial parameter in region 1 as

1.At each xi position, starting at i = 0, if p1i < 0, the next point along the
ellipse centered on (0, 0) is (xi + 1, yi) and

otherwise, the next point is (xi + 1, yi – 1) and

and continue until


Midpoint Ellipse Algorithm
1.(x0, y0) is the last position calculated in region 1. Calculate the initial
parameter in region 2 as

1.At each yi position, starting at i = 0, if p2i > 0, the next point along the ellipse
centered on (0, 0) is (xi, yi – 1) and

otherwise, the next point is (xi + 1, yi – 1) and

Use the same incremental calculations as in region 1. Continue until y = 0.


1.For both regions determine symmetry points in the other three quadrants.
2.Move each calculated pixel position (x, y) onto the elliptical path centered on
(xc, yc) and plot the coordinate values
x = x + xc , y = y + yc
Example
rx = 8 , ry = 6
2x = 0 (with increment 2r 2 = 72)
2ry y
2r 2y = 2r 2r 2 = -128)
x x y (with increment -2rx
Region 1
(x
0, y0) = (0, 6)

i pi xi+1, yi+1 2ry2xi+1 2rx2yi+1


0 -332 (1, 6) 72 768
1 -224 (2, 6) 144 768
2 -44 (3, 6) 216 768
3 208 (4, 5) 288 640
4 -108 (5, 5) 360 640
5 288 (6, 4) 432 512
6 244 (7, 3) 504 384 Move out of region 1 since
2ry2x > 2rx2y 70
Example
Region 2
(x0, y0) = (7, 3) (Last position in region 1)

i pi xi+1, yi+1 2ry2xi+1 2rx2yi+1


0 -151 (8, 2) 576 256
1 233 (8, 1) 576 128
2 745 (8, 0) - - Stop at y = 0

6    
5  
4 
3 
2 
1  71
1.Write an algorithm to draw a line using DDA algorithm. Trace the
algorithm with the end points (20,10) and (30,18). 10 Marks
2.Write an algorithm to draw a line using Bresenham’s principle. Trace the
algorithm with the end points (20,10) and (30,18). 10 Marks
3.Explain Midpoint Circle drawing algorithm giving all the decision
parameters used. Trace the algorithm to draw a circle with radius r=10. List
all the Pixel position on the circumference of the circle – centered at origin.
10 Marks
4.Explain Ellipse Midpoint drawing algorithm giving all the decision
parameters used. Trace the algorithm to draw a circle with radius r=8 and r =
6 List all the Pixel position on the circumference of the circle – centered at
origin. 10 Marks
•Color model based on three primary colors. Green
•Three primary color are three axis of a cube. C
•Red, Green, Blue
Y
Blue M
Red
OpenGL Fill-Area Attribute Functions

•To display of filled convex polygon in four steps


1.Define a fill pattern
2.Invoke the polygon-fill routine
3.Active the polygon-fill feature of OpenGL
4.Describe the Polygon to be filled
OpenGL Texture and Interpolation Patterns
OpenGL Wire-Frame Methods

•glPolygonMode( face, displayMode );


Where: face:- GL_FRONT, GL_BACK, GL_FRON_AND_BACK
displayMode:-
GL_POINT (Only edge points)
GL_LINE (Wireframe)
GL_FILL (Default)
Ex: glPolygonMode(GL_FRONT,GL_LINE);

•glEdgeFlag( flag ); // GL_TRUE or GL_FALSE for line mode

glPloygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_POLYGON);
glVertex3fv(v1);
glEdgeFlag(GL_FALSE);
glVertex3fv(v2);
glEdgeFlag(GL_TRUE);
glVertex3fv(v3);
glEnd();
OpenGL Front-Face Function

•glFrontFace( vertexOrder );
or
•glFrontFace( faceOrder ); // GL_CW or GL_CCW
Color model based on three primary colors. Green
Three primary color are three axis of a cube. C
Red, Green, Blue Y
Blue M
Red
OpenGL Fill-Area Attribute Functions

To display of filled convex polygon in four steps


1.Define a fill pattern
2.Invoke the polygon-fill routine
3.Active the polygon-fill feature of OpenGL
4.Describe the Polygon to be filled
OpenGL Fill-Pattern Function
OpenGL Texture and Interpolation Patterns
OpenGL Wire-Frame Methods

glPolygonMode( face, displayMode );


Where: face:- GL_FRONT, GL_BACK, GL_FRON_AND_BACK
displayMode:-
GL_POINT (Only edge points)
GL_LINE (Wireframe)
GL_FILL (Default)
Ex: glPolygonMode(GL_FRONT,GL_LINE);
glEdgeFlag( flag ); // GL_TRUE or GL_FALSE for line mode

glPloygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_POLYGON);
glVertex3fv(v1);
glEdgeFlag(GL_FALSE);
glVertex3fv(v2);
glEdgeFlag(GL_TRUE);
glVertex3fv(v3);
glEnd();
OpenGL Front-Face Function

glFrontFace( vertexOrder );
or
glFrontFace( faceOrder ); // GL_CW or GL_CCW
Polygon Fill Areas

Convex Concave
E5
(E1xE2)z>0
(E2xE3)z>0
<180o (E3xE4)z<0 E4
(E4xE5)z>0 E6
(E5xE6)z>0 >180o E3

E1 E2
Splitting concave polygon
•Vector Method

The cross product E j × Ek for two successive edge vectors is a vector perpendicular
to the xy plane with z component equal to Ejx Eky − EkxEjy:
•Rotational Method
Inside-Outside Testing

Odd-even rule (easy implementation) Non-zero winding rule


= crossing, odd parity rule, even-odd rule Clockwise edges: +1
Crossed odd edges : inside point Counterclockwise edges : –1
Crossed even edges : outside point Don’t fill while total 0

–1 –1 +1 +1
Polygon Tables

VERTEX TABLE EDGE TABLE POLYGON-


SURFACE TABLE
V1: x1 y1 z1
E1 : V 1, V 2
E2 : V 2, V 3 S1 : E1, E 2, E3
V2: x2 y2 z2
E3 : V 3, V 1 S2 : E 3, E4, E5, E6
V3: x3 y3 z3 V1
E4 : V 3, V 4
V4: x4 y4 z4
E5 : V 4, V 5
V5: x5 y5 z5
E6 : V 5, V 1
E
E E 6
1 3
S1 S2
V5

E V3
E E
2
V2 4 5
V4
Plane Equations

(x,y,z)
Surface Normal

Surface (plane) equation :


Ax+By+Cz+D=0 y
N = (V1-V2)x(V1-V3)
T V1
= [ A B C]
If P is any point on the plane :
V2
N•P+D = 0
N•P = -D V3

x
z
General Scan-Line Polygon-Fill Algorithm

This algorithm works by intersecting scanline with polygon edges and fills the
polygon between pairs of intersection.
Step 1:Find out the ymin and ymax from the given polygon.

Step 2:Scanline intersects with each edge of the polygon from ymin to ymax.name each intersection point of the polygon.as per
the above figure , they are named as P0,P1,P2,P3.
Step 3:Sort the intersection point in the increasing order of x coordinate,that is
(P0,P1),(P1,P2),(P2,P3).

Step 4:Fill all those pair of coordinates that are inside polygons and ignore the alternate pairs.
Fill methods for areas with Irregular boundaries

Boundary Fill algorithm


The Boundary fill algorithm works as its name. This algorithm picks a point inside an
object and starts to fill until it hits the boundary of the object. The color of the
boundary and the color that we fill should be different for this algorithm to work.
The boundary fill algorithm can be implemented by 4-connected pixels or 8-
connected pixels.
4-connected vs. 8-connected

Start point

4-connected 8-connected
void boundaryFill4 (int x, int y, int fillColor, int borderColor)
{
int interiorColor;
/* Set current color to fillColor, then perform following oprations. */
getPixel (x, y, interiorColor);
if ((interiorColor != borderColor) && (interiorColor != fillColor))
{
setPixel (x, y); // Set color of pixel to fillColor.
boundaryFill4 (x + 1, y , fillColor, borderColor);
boundaryFill4 (x - 1, y , fillColor, borderColor);
boundaryFill4 (x , y + 1, fillColor, borderColor);
boundaryFill4 (x , y - 1, fillColor, borderColor)
}
}
Flood Fill Algorithm

Sometimes we come across an object where we want to fill the area and its boundary
with different colors.
This algorithm replaces the interior color of the object with fill color.It is looking for
all adjacent pixels that are a part of the interior,when no more pixels of the original
interior color exist, the algorithm is completed.
void floodFill4 (int x, int y, int fillColor, int interiorColor)
{
int color;
/* Set current color to fillColor, then perform following operations. */
getPixel (x, y, color);
if (color = interiorColor)
{
setPixel (x, y); // Set color of pixel to fillColor.
floodFill4 (x + 1, y, fillColor, interiorColor);
floodFill4 (x - 1, y, fillColor, interiorColor);
floodFill4 (x, y + 1, fillColor, interiorColor);
floodFill4 (x, y - 1, fillColor, interiorColor)
}
}

You might also like