0% found this document useful (0 votes)
32 views22 pages

Tut1 2 3

The document discusses the key stages in the OpenGL rendering pipeline including display lists, evaluators, per-vertex operations, primitive assembly, pixel operations, texture assembly, rasterization, and fragment operations. It also discusses related libraries like GLUT and GLU that build upon OpenGL functionality.

Uploaded by

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

Tut1 2 3

The document discusses the key stages in the OpenGL rendering pipeline including display lists, evaluators, per-vertex operations, primitive assembly, pixel operations, texture assembly, rasterization, and fragment operations. It also discusses related libraries like GLUT and GLU that build upon OpenGL functionality.

Uploaded by

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

1. Implement basic OPENGL primitives.

1.1 INTRODUCTION
Computer graphics are graphics created using computers and, more generally, the representation
and manipulation of image data by a computer hardware and software. The development of
computer graphics, or simply referred to as CG, has made computers easier to interact with, and
better for understanding and interpreting many types of data. Developments in computer
graphics have had a profound impact on many types of media and have revolutionized the
animation and video game industry. 2D computer graphics are digital images—mostly from two-
dimensional models, such as 2D geometric models, text (vector array), and 2D data. 3D
computer graphics in contrast to 2D computer graphics are graphics that use a three-dimensional
representation of geometric data that is stored in the computer for the purposes of performing
calculations and rendering images.
1.2 OPEN GL OpenGL is the most extensively documented 3D graphics API(Application
Program Interface) to date. Information regarding OpenGL is all over the Web and in print. It is
impossible to exhaustively list all sources of OpenGL information. OpenGL programs are
typically written in C and C++. One can also program OpenGL from Delphi (a Pascal-like
language), Basic, Fortran, Ada, and other langauges. To compile and link OpenGL programs,
one will need OpenGL header files. To run OpenGL programs one may need shared or
dynamically loaded OpenGL libraries, or a vendor-specific OpenGL Installable Client Driver
(ICD).
1.3 GLUT The OpenGL Utility Toolkit (GLUT) is a library of utilities for OpenGL programs,
which primarily perform system-level I/O with the host operating system. Functions performed
include window definition, window control, and monitoring of keyboard and mouse input.
Routines for drawing a number of geometric primitives (both in solid and wireframe mode) are
also provided, including cubes, spheres, and cylinders. GLUT even has some limited support for
creating pop-up menus. The two aims of GLUT are to allow the creation of rather portable code
between operating systems (GLUT is cross-platform) and to make learning OpenGL easier. All
GLUT functions start with the glut prefix (for example, glutPostRedisplay marks the current
window as needing to be redrawn).
1.4 KEY STAGES IN THE OPENGL RENDERING PIPELINE:
 Display Lists

All data, whether it describes geometry or pixels, can be saved in a display list for current or later
use. (The alternative to retaining data in a display list is processing the data immediately - also
known as immediate mode.) When a display list is executed, the retained data is sent from the
display list just as if it were sent by the application in immediate mode

 Evaluators
All geometric primitives are eventually described by vertices. Parametric curves and surfaces
may be initially described by control points and polynomial functions called basis functions.
Evaluators provide a method to derive the vertices used to represent the surface from the control
points. The method is a polynomial mapping, which can produce surface normal, texture
coordinates, colors, and spatial coordinate values from the control points.

 Per-Vertex Operations
For vertex data, next is the "per-vertex operations" stage, which converts the vertices into
primitives. Some vertex data (for example, spatial coordinates) are transformed by 4 x 4 floating-
point matrices. Spatial coordinates are projected from a position in the 3D world to a position on
your screen. If advanced features are enabled, this stage is even busier. If texturing is used,
texture coordinates may be generated and transformed here. If lighting is enabled, the lighting
calculations are performed using the transformed vertex, surface normal, light source position,
material properties, and other lighting information to produce a color value.

 Primitive Assembly

Clipping, a major part of primitive assembly, is the elimination of portions of geometry which
fall outside a half-space, defined by a plane. Point clipping simply passes or rejects vertices; line
or polygon clipping can add additional vertices depending upon how the line or polygon is
clipped. In some cases, this is followed by perspective division, which makes distant geometric
objects appear smaller than closer objects. Then viewport and depth (z coordinate) operations are
applied. If culling is enabled and the primitive is a polygon, it then may be rejected by a culling
test. Depending upon the polygon mode, a polygon may be drawn as points or lines. The results
of this stage are complete geometric primitives, which are the transformed and clipped vertices
with related color, depth, and sometimes texture-coordinate values and guidelines for the
rasterization step.
 Pixel Operations

While geometric data takes one path through the OpenGL rendering pipeline, pixel data takes a
different route. Pixels from an array in system memory are first unpacked from one of a variety
of formats into the proper number of components. Next the data is scaled, biased, and processed
by a pixel map. The results are clamped and then either written into texture memory or sent to
the rasterization step If pixel data is read from the frame buffer, pixel-transfer operations (scale,
bias, mapping, and clamping) are performed. Then these results are packed into an appropriate
format and returned to an array in system memory.
There are special pixel copy operations to copy data in the framebuffer to other parts of the
framebuffer or to the texture memory. A single pass is made through the pixel transfer operations
before the data is written to the texture memory or back to the framebuffer.
 Texture Assembly

An OpenGL application may wish to apply texture images onto geometric objects to make them
look more realistic. If several texture images are used, it’s wise to put them into texture objects
so that you can easily switch among them. Some OpenGL implementations may have special
resources to accelerate texture performance. There may be specialized, high-performance texture
memory. If this memory is available, the texture objects may be prioritized to control the use of
this limited and valuable resource.
 Rasterization

Rasterization is the conversion of both geometric and pixel data into fragments. Each fragment
square corresponds to a pixel in the framebuffer. Line and polygon stipples, line width, point
size, shading model, and coverage calculations to support antialiasing are taken into
consideration as vertices are connected into lines or the interior pixels are calculated for a filled
polygon. Color and depth values are assigned for each fragment square.
 Fragment Operations

Before values are actually stored into the framebuffer, a series of operations are performed that
may alter or even throw out fragments. All these operations can be enabled or disabled. The first
operation which may be encountered is texturing, where a texel (texture element) is generated
from texture memory for each fragment and applied to the fragment. Then fog calculations may
be applied, followed by the scissor test, the alpha test, the stencil test, and the depth-buffer test
(the depth buffer is for hidden-surface removal). Failing an enabled test may end the continued
processing of a fragment’s square. Then, blending, dithering, logical operation, and masking by a
bitmask may be performed.Finally, the thoroughly processedfragment is drawn into the
appropriate buffer, where it has finally advanced to be a pixel and achieved its final resting place.

1.5 OpenGL-Related Libraries


OpenGL provides a powerful but primitive set of rendering commands, and all higher-level
drawing must be done in terms of these commands. Also, OpenGL programs have to use the
underlying mechanisms of the windowing system. A number of libraries exist to allow you to
simplify your programming tasks, including the following:
The OpenGL Utility Library (GLU) contains several routines that use lower-level OpenGL
commands to perform such tasks as setting up matrices for specific viewing orientations and
projections, performing polygon tessellation, and rendering surfaces. This library is provided as
part of every OpenGL implementation. Portions of the GLU are described in the OpenGL For
every window system, there is a library that extends the functionality of that window system to
support OpenGL rendering. For machines that use the X Window System, the OpenGL
Extension to the X Window System (GLX) is provided as an adjunct to OpenGL. GLX routines
use the prefix glX. For Microsoft Windows, the WGL routines provide the Windows to OpenGL
interface. All WGL routines use the prefix wgl. For IBM OS/2, the PGL is the Presentation
Manager to OpenGL interface, and its routines use the prefix pgl. The OpenGL Utility Toolkit
(GLUT) is a window system-independent toolkit, written by Mark Kilgard, to hide the
complexities of differing window system APIs. Open Inventor is an object-oriented toolkit based
on OpenGL which provides objects and methods for creating interactive three-dimensional
graphics applications. Open Inventor, which is written in C++, provides prebuilt objects and a
built-in event model for user interaction, high-level application components for creating and
editing three-dimensional scenes, and the ability to print objects and exchange data in other
graphics formats. Open Inventor is separate from OpenGL.

1.6 GLUT, the OpenGL Utility Toolkit


As you know, OpenGL contains rendering commands but is designed to be independent of any
window system or operating system. Consequently, it contains no commands for opening
windows or reading events from the keyboard or mouse. Unfortunately, it’s impossible to write a
complete graphics program without at least opening a window, and most interesting programs
require a bit of user input or other services from the operating system or window system. In
many cases, complete programs make the most interesting examples, so this book uses GLUT to
simplify opening windows, detecting input, and so on. If you have an implementation of
OpenGL and GLUT on your system, the examples in this book should run without change when
linked with them. In addition, since OpenGL drawing commands are limited to those that
generate simple geometric primitives (points, lines, and polygons), GLUT includes several
routines that create more complicated three-dimensional objects such as a sphere, a torus, and a
teapot. This way, snapshots of program output can be interesting to look at. (Note that the
OpenGL Utility Library, GLU, also has quadrics routines that create some of the same three-
dimensional objects as GLUT, such as a sphere, cylinder, or cone.)
GLUT may not be satisfactory for full-featured OpenGL applications, but you may find it a
useful starting point for learning OpenGL. The rest of this section briefly describes a small
subset of GLUT routines so that you can follow the programming examples in the rest of this
book.

1.7 Installation of OPENGL:

Download Codeblocks from following link and follow the instructions given below:
https://drive.google.com/file/d/1UpSJc-NWnIXyOcUVIBUx91mq5A5LopWM/view

Step -1 :Double click on codeblocks-17.12mingw-setup file


While setup set destination folder as : C:\Program Files (x86)\
Once setup is complete----copy following files to respective folder
Step-2 : Copy the glut.h file and paste it into the directory
"C:\ProgramFiles(x86)\CodeBlocks\MinGW\include\GL"
Step-3 : Copy glut32.lib file and paste it into the directory
"C:\Program Files(x86)\CodeBlocks\MinGW\lib"
Step-4 : Copy the glut32.dll and paste it into the directory
"C:\Windows\System32"
Step-5 : Copy the glut32.dll and paste it into the directory
"C:\Windows\SysWOW64"

In Every OpenGL Program Include the Following Header Files:-


#include<windows.h>
#include <GL/glu.h>
#include <GL/glut.h>

On successful installation of Codeblocks—open codeblocks


Click on: Create new project
From list choose GLUT PROJECT
Click on next

2. Implement the DDA algorithm for line drawing.


a) Implement DDA using Mouse.
b) Draw any shape or pattern.
c) Draw Dotted, Dashed and Das-Dot-Dash line
3. Implement Bresenham’s algorithm for line drawing.
a) Draw given pattern.
b) Draw Dotted, Dashed and Das-Dot-Dash line
4. Implement Midpoint and Bresenham’s Circle drawing algorithm.
5. Draw the polygons by using the mouse. (Use DDA algorithm for line drawing).Fill the
polygon with Boundary fill and Flood fill method.
6. Implement 2D translation, sheer, rotation, reflection and scaling transformations on equilateral
triangle or rhombus.
7. Implement Sutherland Hodgman algorithm to clip any given polygon. Provide the vertices of
the polygon to be clipped and pattern of clipping interactively.
8. Implement 3D Cube translation, scaling and rotation.
a) Translations in x, y, z directions
Please Select GLUT Location
Click on Browse --- Select path as C:\Program Files (x86)\CodeBlocks\MinGW

If you fail/forgot to set


this path then your
program will give error

Click on Next Button


Click on Finish Button

On left hand side, you will see workplace --Click on + symbol of Sources folder -- Double click
on main.cpp

Go to Build Option in menus--Build –main.cpp


You will get following error because we have not added header files for glu & glut functions
Add header files in header file section i.e. at line number 139

Build & Run ---main.cpp


You will get following O/P---Now your Codebox is ready for openGL programming

Basic Structure of OpenGL Program:


You can create c/c++ program , We will start with C program.We start C program with void
main()---here we are using IDE so void main will not work , it should return something…
So, int main { return 0; }
Now we will initialize GLUT Function
Glut is very first API-utility API
Syntax: glutInit();
Eg. Void main()
{
glutInit();
}
NORMALLY WHEN YOU START c program, by default it is going to console program i.e.
black screen we see. We need interactive interface with window-i.e to create/manage
window,So, we need to initialize glut.
• Glut takes two parameters , we are going to pass these two parameters through main
function, hence our main function should have two parameters.
• As we know that command line parameters to main function are
i)Argument count ii) Argument string/array of string
Eg. int main( int C, Char *V[])
**Here IDE will pass parameter to main function
Once we have parameters in main function , we will pass these parameters to glut function
• First parameter will be address of argument and second parameter will be name of second
argument (because here second parameter is already the pointer)
int main(int c, char *v[])
{
glutInit(&c,v);
return 0;
}
Once this is done, your program is ready to work in graphics mode
• Next job is to create window using CreateWindow(); function which belongs to glut
library. This function is having one parameter.
int main(int c, char *v[])
{
glutInit(&c,v);
glutCreateWindow("Basic of OpenGL");
return 0;
• Compile the program-You will get error( Undefined reference to glutInit()
Here problem is that we are using glut function from openGl , so we need to include the
header file
#include <GL/glu.h>
#include <GL/glut.h>
int main(int c, char *v[])
{
glutInit(&c,v);
glutCreateWindow("Basic of OpenGL");
return 0;
}
Build & run the above program, whatever window we created, it is not visible to us
because program runs fast and after executing return 0 statement program is
immediately coming to console.
• We have to include glutMainLoop(); function
• glutMainLoop(); puts the program in an infinite event loop. This will keep on executing
main() function in loop and will be starting of your window.
#include <GL/glu.h>
#include <GL/glut.h>
int main(int c, char *v[])
{
glutInit(&c,v);
glutCreateWindow("Basic of OpenGL");
glutMainLoop();
return 0;
}
Build & Run above program.
Window will appear and disappear immediately. (or sometime gives the error like “ no
display callback function” So add Display function before glutMainLoop(), this takes one
parameter. This Parameter is pointer to another(any) function name.
Syntax: glutDisplayFunc(UserDefineFunction)
Eg. glutDisplayFunc(Draw);
// You can use inbuilt function also as parameter
Define function before int main ();
#include <GL/glu.h>
#include <GL/glut.h>
void Draw()
{
}
int main(int c, char *v[])
{
glutInit(&c,v);
glutCreateWindow("Basic of OpenGL");
glutDisplayFunc(Draw); // User Defined Function
glutMainLoop();
return 0;
}
Build & Run
You will get window. Default window size is 300*300.Now we want to increase the size of
window.
Add following function before CreateWindow() function
glutInitWindowSize(600,500);

#include <GL/glu.h>
#include <GL/glut.h>
void Draw()
{
}
int main(int c, char *v[])
{
glutInit(&c,v);
glutInitWindowSize(600,500)
glutCreateWindow("Basic of OpenGL");
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}

• Build & run


• Default window position is (0,0).You can change default window position to specific
window position using following function.

#include <GL/glu.h>
#include <GL/glut.h>
void Draw()
{
}
int main(int c, char *v[])
{
glutInit(&c,v);
glutInitWindowPosition(100,50);
glutInitWindowSize(600,500);
glutCreateWindow("Basic of OpenGL");
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}
• Mode of Display---2D/3D
• Function syntax:
• glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE) ;
#include <GL/glu.h>
#include <GL/glut.h>
void Draw()
{
}
int main(int c, char *v[])
{
glutInit(&c,v);
glutInitWindowPosition(100,50);
glutInitWindowSize(600,500);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutCreateWindow("Basic of OpenGL");

glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}
Build & Run.
You will not see any effect but this will be helpful when you will convert the 2D image to 3D
image.

• The glClearColor function specifies the red, green, blue, and alpha values used
by glClear to clear the color buffers. Values specified by glClearColor are clamped to
the range [0,1].
#include <GL/glu.h>
#include <GL/glut.h>
void Draw()
{
}
int main(int c, char *v[])
{
glutInit(&c,v);
glutInitWindowPosition(100,50);
glutInitWindowSize(600,500);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutCreateWindow("Basic of OpenGL");
glClearColor(0,0,0,1);
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}

• glColor—Set Drawing Color


• glcolor sets a new four-valued RGB color. glcolor has two major variants: glcolor3 and
glcolor4. glcolor3 variants specify new red, green, and blue values explicitly and set the current
alpha value to 1.0 (full intensity) implicitly. glcolor4 variants specify all four color components
explicitly.
#include <GL/glu.h>
#include <GL/glut.h>
void Draw()
{
}
int main(int c, char *v[])
{
glutInit(&c,v);
glutInitWindowPosition(100,50);
glutInitWindowSize(600,500);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutCreateWindow("Basic of OpenGL");
glClearColor(0,0,0,1);
glColor3f(1,0,0);
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}

• When we create window using openGL, window is divided as per following in X & Y
coordinates ranging from +1 to -1

+1

(-0.5,0.5) (0.5,0.5)
-1 X +1

(-0.5,-0.5) (0.5,-0.5)

-1
let us study the openGL coordinate system
Diagram shows default coordinate system for openGL
-X axis value is -1 +X axis value is +1
-Y axis value is -1 +Y axis value is +1
Min X axis value is -1 max X axis value is +1
Min Y axis value is -1 maxY axis value is +1
• Let us draw square/rectangle
• To draw square , we will need four coordinates/points.These points in openGL are called
as vertex or vertices.
• GO to Draw(); Function in program
• First function to call in Draw() is to clear background
• Syntax: glClear(GL_COLOR_BUFFER_BIT);
• Define vertices:
glvertex2f(-0.5,0.5);
glvertex2f(0.5,0.5); We will use this points to draw basic primitives
glvertex2f(0.5,-0.5);
glvertex2f(-0.5,-0.5
• Put all points within glBegin(); and glEnd();
glBegin();
glvertex2f(-0.5,0.5);
glvertex2f(0.5,0.5);
glvertex2f(0.5,-0.5);
glvertex2f(-0.5,-0.5)
glEnd();
Now you can use these points to draw any premitives
Eg.
glBegin(GL_POINTS);
glVertex2f(-0.5,0.5);
glVertex2f(0.5,0.5);
glVertex2f(0.5,-0.5);
glVertex2f(-0.5,-0.5);
glEnd();

#include <GL/glu.h>
#include <GL/glut.h>
void Draw()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
glVertex2f(-0.5,0.5);
glVertex2f(0.5,0.5);
glVertex2f(0.5,-0.5);
glVertex2f(-0.5,-0.5);
glEnd();
}
int main(int c, char *v[])
{
glutInit(&c,v);
glutInitWindowPosition(100,50);
glutInitWindowSize(600,500);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutCreateWindow("Basic of OpenGL");
glClearColor(0,0,0,1);
glColor3f(1,0,0);
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}
Build & Run
You will not able see anything on screen.Because whatever we draw within glBegin() and
glEnd()
We have to flush the same.
#include <GL/glu.h>
#include <GL/glut.h>
void Draw()
{
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(5);
glBegin(GL_POINTS);
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 c, char *v[])
{
glutInit(&c,v);
glutInitWindowPosition(100,50);
glutInitWindowSize(600,500);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutCreateWindow("Basic of OpenGL");
glClearColor(0,0,0,1);
glColor3f(1,0,0);
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}

OpenGL Primitives:
1.What is Computer Graphics? Answer: Computer graphics are graphics created using computers
and, more generally, the representation and manipulation of image data by a computer.
2. What is OpenGL? Answer: OpenGL is the most extensively documented 3D graphics API
(Application Program Interface) to date. It is used to create Graphics.
3. What is GLUT? Answer: The OpenGL Utility Toolkit (GLUT) is a library of utilities for
OpenGL programs, which primarily perform system-level I/O with the host operating system.
4. What are the applications of Computer Graphics? Answer: Gaming Industry, Animation
Industry and Medical Image Processing Industries. The sum total of these industries is a Multi
Billion Dollar Market. Jobs will continue to increase in this arena in the future.

2. Implement the DDA algorithm for line drawing.


Problem Definition: Write a program to draw line using DDA algorithm .
2.1 Prerequisite: Basic primitives of computer graphics and concepts of OOP.
2.2 Learning Objective:
Understand the functions available in Graphics library.
2.3 Relevant Theory / Literature Survey:
Raster Scan Display:
When the beam reaches the bottom of the screen, it is made OFF and rapidly retracted
back to top left to start again. A display produced in this way is called Raster Scan
Display.
The refresh process is independent of the complexity of the image.
Sequences of operations performed in raster scan are performed through following components:
a) Graphics Commands.
b) Display Conversion (Scan Conversion)
c) Frame buffer.
d) Display Controller
e) Visual Display Unit (VDU).
Characteristics:
i. It is very cost effective, even inexpensive.
ii. It has availability of large memory and has high refresh rate.
iii. It has ability to display areas filled with solid colors and patterns.
Block Diagram:

Vector Scan Display:


In vector scan display, the beam is moved between the endpoints of graphics primitives.
It flickers when the number of primitives in the buffer becomes too large.

Characteristics:
i. This is also called as Random Scan Display.
ii. It draws a continuous and smooth line.
iii. It only draws lines and characters and is more costly.

Line:
It is the path between two end points.
Any point (x, y) on the line must follow the line equation:
Point is the fundamental element of the picture representation. It is nothing but the position in a
plane defined as either pairs or triplets of numbers depending whether the data are two or three
dimensional. Thus (x1, y1) or (x1, y1, z1) would represent a point two or three dimensional
space.
Two points used to specify line by below equation
y = m * x + b, where
– m is the slope of the line.
– b is a constant that represent the intercept on y-axis.
If we have two end points, (x0, y0) and (x1, y1), then the slope of the line (m) between those
points can be calculated as:
m = Δy / Δx = (y1 – y0) / (x1 – x0)
Draw a line with the help of line equation is very time consuming because it’s required lots of
calculation. A cathode ray tube (CRT) raster display is considered a matrix of discrete finite area
cells (pixels), it is not possible to draw a straight line directly from one point to another. The
process of determining which pixels provide the best approximation to the desired line is called
rasterization.
To draw a line, we can use two algorithms:
i) DDA (Digital Differential Analyzer)/Vector Generation Algorithm.
ii) Bresenham’s Line Algorithm.
1. DDA Line Drawing Algorithm:
Digital Differential Analyzer (DDA) algorithm is the simple line generation algorithm. It is the
simplest algorithm and it does not require special skills for implementation. It is a faster method
for calculating pixel positions than the direct use of equation y=mx + b. It eliminates
the multiplication in the equation by making use of raster characteristics, so that appropriate
increments are applied in the x or y direction to find the pixel positions along the line path.
Disadvantages of DDA Algorithm
1. Floating point arithmetic in DDA algorithm is still time-consuming.
2. The algorithm is orientation dependent. Hence end point accuracy is poor.
Algorithm for DDA Line:
1. Start
2. Read the line end points (x1,y1) and (x2,y2) such that they are not equal.
3. Calculate the difference between two end points.
dx = x1 – x2
dy = y1 - y2
6. If dx >= dy and x1 <= x2 then //gentle slope lines
Increment x by 1
Increment y by m
Else if dx >= dy and x1 > x2 then //gentle slope lines
Increment x by -1
Increment y by -m
Else if dx < dy and y1 <= y2 then //steep/sharp slope lines
Increment x by 1/m
Increment y by 1
Else if dx < dy and y1 > y2 then //steep/sharp slope lines
Increment x by -1/m
Increment y by -1
7. plot xincrement and yincrement
8. repeat step 6 until other end point is reach
9. Closegraph
10. Stop.
2.4 Questions:-
Q 1: State advantages of DDA Line drawing algorithm?
Q 3: What is long form of DDA?
Q 6: Which line is clearer DDA or Line generated by Equation?
2.5 Conclusion:-
In This way we have studied that how to draw a line using DDA Algorithms.

3. Problem Definition :Implement Bresenham’s algorithm for


line drawing.
3.1 Prerequisite: Basic primitives of computer graphics and concepts of OOP.
3.2 Learning Objective:
Understand the functions available in Graphics library.
2. Bresenham’s Line Drawing Algorithm:
Bresenham’s is another incremental scan-conversion algorithm. It is named AfterJack Bresenham
who worked at IBM for 27 years before entering academics. He had developed this algorithm in early
1960 at IBM.. The biggest advantage of this algorithm is that it uses only integer calculations.When
we have a point (xk, yk), then we must decide whether to draw the point (xk+1, yk) or (xk+1,
yk+1).Note that, at all cases, we move to xk+1, still we must decide to move to yk or yk+1. The
increment in the other variable is determined by examining the distance between the actual line
location and the nearest pixel. The distance is called decision variable or the error.
As shown in figure the line does not pass through all raster points. It is passes through raster point
(0,0). It is seen that the intercept of line Xk+1 is closer to the line Yk+1 than to the line Yk..
Algorithm for Bresenham’s Line:
1. Start
2. Declare the variables and gDriver = DETECT and gMode
3. Initialize the graphics mode using initgraph( )
4. Read the line end points (x1,y1) and (x2,y2) such that they are not equal.
5. Calculate dx=x2-x1 and dy=y2-y1
6. x=x1 and y=y1 [Initialize starting point]
7. e=2*dy-dx [Initialize value of decision variable]
8. i=1
9. plot(x,y)
10. while(e>=0)
{
y=y+1
e=e - 2*dx
}
x=x+1
e=e + 2*dy
11. i=i+1
12. if(i<=dx)then go to step 9
13. Closegraph
14. Stop.
1.4 Questions:-
Q 1: Which algorithm is faster in DDA and Bresenham’s?
Q 2: State advantages of Bresenham’s Line drawing algorithm?
Q 3: Difference between DDA Line and Bresenham’s line algorithm?
Q 4: Which Algorithm is efficient for line drawing?
1.5 Conclusion:-
In This way we have studied that how to draw a line using Bresenham’s Algorithm.

You might also like