0% found this document useful (0 votes)
36 views29 pages

CG Unit 1

These are the question and answer for the unit no. Of cg

Uploaded by

kiran more
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)
36 views29 pages

CG Unit 1

These are the question and answer for the unit no. Of cg

Uploaded by

kiran more
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/ 29

What is computer Graphics?

Computer graphics is an art of drawing pictures, lines, charts, etc. using computers with
the help of programming. Computer graphics image is made up of number of pixels. Pixel
is the smallest addressable graphical unit represented on the computer screen.
Introduction
 Computer is information processing machine. User needs to communicate with
computer and the computer graphics is one of the most effective and commonly used
ways of communication with the user.
 It displays the information in the form of graphical objects such as pictures, charts,
diagram and graphs.
 Graphical objects convey more information in less time and easily
understandable formats for example statically graph shown in stock exchange.
 In computer graphics picture or graphics objects are presented as a collection of
discrete pixels.
 We can control intensity and color of pixel which decide how picture look like.
 The special procedure determines which pixel will provide the best
approximation to the desired picture or graphics object this process is known as
Rasterization.
 The process of representing continuous picture or graphics object as a
collection of discrete pixels is called Scan Conversion.

Advantages of computer graphics


 Computer graphics is one of the most effective and commonly used ways of
communication with computer.
 It provides tools for producing picture of “real-world” as well as synthetic objects such
as mathematical
 surfaces in 4D and of data that have no inherent geometry such as survey result.
 It has ability to show moving pictures thus possible to produce animations with
computer graphics.
 With the use of computer graphics we can control the animation by adjusting the speed,
portion of picture in view the amount of detail shown and so on.
 It provides tools called motion dynamics. In which user can move objects as well as
observes as per requirement for example walk throw made by builder to show flat
interior and surrounding.
 It provides facility called update dynamics. With this we can change the shape color and
other properties of object.
 Now in recent development of digital signal processing and audio synthesis chip the
interactive graphics can now provide audio feedback along with the graphical feed
backs.

Application of computer graphics


 User interface: - Visual object which we observe on screen which communicates with
user is one of the most useful applications of the computer graphics.
 Plotting of graphics and chart in industry, business, government and educational
organizations drawing like bars, pie-charts, histogram’s are very useful for quick and
good decision making.
 Office automation and desktop publishing: - It is used for creation and dissemination of
information. It is used in in-house creation and printing of documents which contains
text, tables, graphs and other forms of drawn or scanned images or picture.
 Computer aided drafting and design: - It uses graphics to design components and
system such as automobile bodies structures of building etc.
 Simulation and animation: - Use of graphics in simulation makes mathematic models
and mechanical systems more realistic and easy to study.
 Art and commerce: - There are many tools provided by graphics which allows used to
make their picture animated and attracted which are used in advertising.
 Process control: - Now a day’s automation is used which is graphically displayed on the
screen.
 Cartography: - Computer graphics is also used to represent geographic maps, weather
maps, oceanographic charts etc.
 Education and training: - Computer graphics can be used to generate models of
physical, financial and economic systems. These models can be used as educational
aids.
 Image processing: - It is used to process image by changing property of the image.

graphics primitives - pixel, resolution, aspect ratio, frame buffer


A primitive is a low level object or operation from which higher-level, more complex objects
and operations can be constructed. In graphics, primitives are basic elements, such as lines,
curves, and polygons, which can be combined to create more complex graphical images. In
programming, primitives are the basic operations supported by the programming language. To
creative any drawing in the computer these primitives form a part of the software and the type
of display to store these in the form of data is important.
Graphics Primitive is a basic object that is essential for the creation or construction of
complex images. Graphics is constructed from three basic elements, as opposed to the great
variety of graphics applications. The most basic of these elmental structures is the pixel, short
for picture element.
Pixel

A pixel is a point of light. It is just one tiny dot on the raster displays. Though it has no
structure, it is definitely a building block and hence it can be considered as the graphics
primitive. The resolution of CRT is related to the dot size, the diameter of a single dot. A
resolution of 100 dots lines/inch implies a dot size of 0.01 inch. The ratio of the distance
between the centres of two adjacent horizontal pixels to that of the vertical ones is called the
pixel ratio. Pixel ratio should be considered in line-generating algorithms.
Line

Line, especially straight lines, constitute the basic building block of Line graphs, bar and pie
charts, two and three-dimensional graphs of mathematical functions, engineering drawings and
architectural plans. In computer graphics, straight line is so basic in creating images that we
call it a graphics primitive. Straight lines can be developed in two different ways. A structural
method determines which pixels should be set before drawing the line; a conditional
method tests certain conditions to find which pixel should be set next.
Polygon

A polygon is a closed area of image bounded by straight or curved lines and filled with one
solid color. Since images are two dimensional, a polygon is a closed planar figure.A polygon,
is an important graphics primitive. So often we want to handle polygon as a single entity, as
images of objects from the real world consist in large, part of polygons.
Display file

A display file is a set of uncorrelated data, such as a histogram array or bivariate array. The
arrays are filled event by event from a list data in order to create a display. The saved arrays
usually take up far less disk space, but can the data can no longer be gated.
Frame buffer

The video output device which drives a video display from the memory buffer containing a
complete set of data is known as frame buffer. The image is stored in terms of pixel by pixel.
The memory can be discs, Integrated circuits etc.,
Resolution
the term resolution refers to the total number of count of pixels in an digital image. For
example. If an image has M rows and N columns, then its resolution can be defined as M X
N.
If we define resolution as the total number of pixels, then pixel resolution can be defined with
set of two numbers. The first number the width of the picture, or the pixels across columns,
and the second number is height of the picture, or the pixels across its width.
We can say that the higher is the pixel resolution, the higher is the quality of the image.
e.g. You have probably seen that in your own computer settings, you have monitor resolution
of 800 x 600, 640 x 480 e.t.c

Aspect ratio

Aspect ratio is the ratio between width of an image and the height of an image. It is
commonly explained as two numbers separated by a colon (8:9). This ratio differs in different
images, and in different screens. The common aspect ratios are:
1.33:1, 1.37:1, 1.43:1, 1.50:1, 1.56:1, 1.66:1, 1.75:1, 1.78:1, 1.85:1, 2.00:1, e.t.c
Advantage
Aspect ratio maintains a balance between the appearance of an image on the screen, means it
maintains a ratio between horizontal and vertical pixels. It does not let the image to get
distorted when aspect ratio is increased.
Display Devices

The display device is an output device used to represent the information in the form of images
(visual form). Display systems are mostly called a video monitor or Video display unit (VDU).
Display devices are designed to model, display, view, or display information. The purpose of
display technology is to simplify information sharing.
There are some display devices given below:
1. Cathode-Ray Tube(CRT)
2. Color CRT Monitor
3. Liquid crystal display(LCD)
4. Light Emitting Diode(LED)
5. Direct View Storage Tubes(DVST)
6. Plasma Display
7. 3D Display
Description pending……………………

Introduction to OpenGL
OpenGL is a software interface that allows the programmer to create 2D and 3D graphics
images. OpenGL is both a standard API and the implementation of that API. You can call
the functions that comprise OpenGL from a program you write and expect to see the same
results no matter where your program is running. OpenGL is independent of the hardware,
operating, and windowing systems in use. The fact that it is windowing-system
independent, makes it portable. OpenGL program must interface with the windowing
system of the platform where the graphics are to be displayed.
Therefore, a number of windowing toolkits have been developed for use with OpenGL.
OpenGL functions in a client/server environment. That is, the application program
producing the graphics may run on a machine other
than the one on which the graphics are displayed. The server part of OpenGL, which runs
on the workstation where the graphics are displayed, can access whatever physical
graphics device or frame buffer is available
on that machine.
OpenGL's rendering commands, however are "primitive". You can tell theprogram to draw
points, lines, and polygons, and you have to build more complex entities upon these. There are
no special-purpose functions that you can call to create graphs, contour plots, maps, or any of
the other elements we are used to getting from "old standby programs”. With OpenGL, you
have to build these
things up yourself.
With OpenGL any commands that you execute are executed immediately. That is, when you
tell the program to draw something, it does it right away. You also have the option of putting
commands into display lists. A display list is a noteditable list of OpenGL commands stored
for later execution. You can execute the same display list more than once. For example, you
can use display lists to redraw the graphics whenever the user resizes the window. You can use
a display list to draw the same shape more than once if it repeats as an element of the picture.

OpenGL is a hardware-independent, operating system independent, vendor neutral


graphics API specification. Many vendors provide implementations of this
specification for a variety of hardware platforms.

OpenGL has been designed using a client/server paradigm, allowing the client application and
the graphics server controlling the display hardware to exist on the same or separate machines.
The network is transparent to the application.

OpenGL is window system independent, and therefore contains no windowing operations or


mechanisms for user input. Also, OpenGL does not provide direct support for complex
geometrical shapes, such as cubes or spheres. These must be built up from supported
primitives.

Some features of OpenGL include the following:


 Geometric and raster primitives
 RGBA or color index mode
 Display list or immediate mode
 Viewing and modeling transformations
 Lighting and Shading
 Hidden surface removal (Depth Buffer)
 Alpha Blending (Translucency)
 Anti-aliasing
 Texture Mapping
 Atmospheric Effects (Fog, Smoke, Haze)
 Feedback and Selection
 Stencil Planes
 Accumulation Buffer
 Depth Cueing
 Wireframes
 Motion blur
Also available with OpenGL are the following three libraries:
 The OpenGL Utility Library (GLU), which contains several routines that use lower-
level OpenGL commands to perform such tasks as setting up matrices for specific
viewing orientations and projections, performing tessellation, and rendering surfaces.
 The OpenGL Extension to the X Window System (GLX) provides a means of creating
an OpenGL context and associating it with an X Window System window.
 The OpenGL Programming Guide Auxiliary Library provides routines for initializing
and opening windows, handling X events and dealing with common complex shapes,
such as cubes, spheres, and cylinders.

OpenGL Pipeline
The OpenGL architecture is structured as a state-based pipeline. Below is a simplified diagram
of this pipeline. Commands enter the pipeline from the left.
Fig Diagram open Gl architecture Structure as a state based pipeline

Commands may either be accumulated in display lists, or processed immediately through the
pipeline. Display lists allow for greater optimization and command reuse, but not all
commands can be put in display lists.

The first stage in the pipeline is the evaluator. This stage effectively takes any polynomial
evaluator commands and evaluates them into their corresponding vertex and attribute
commands.

The second stage is the per-vertex operations, including transformations, lighting, primitive
assembly, clipping, projection, and viewport mapping.

The third stage is rasterization. This stage produces fragments, which are series of framebuffer
addresses and values, from the viewport-mapped primitives as well as bitmaps and pixel
rectangles.

The fourth stage is the per-fragment operations. Before fragments go to the framebuffer, they
may be subjected to a series of conditional tests and modifications, such as blending or z-
buffering.

Parts of the framebuffer may be fed back into the pipeline as pixel rectangles. Texture memory
may be used in the rasterization process when texture mapping is enabled.

OpenGL Drawing Primitives

OpenGL supports several basic primitive types, including points, lines, quadrilaterals, and
geneneral polygons. All of these primitives are specified using a sequence of vertices. The
diagram below shows the basic primitive types, where the numbers indicate the order in which
the vertices have been specified. Note that for the GL_LINES primitive only every second vertex
causes a line segment to be drawn. Similarly, for the GL_TRIANGLES primitive, every third
vertex causes a triangle to be drawn. Note that for
the GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN primitives, a new triangle is produced for
every additional vertex. All of the closed primitives shown below are solid-filled, with the
exception of GL_LINE_LOOP, which only draws lines connecting the vertices.

Fig : OpenGL Drawing Primitives


The following code fragment illustrates an example of how the primitive type is specified and
how the sequence of vertices are passed to OpenGL. It assumes that a window has already
been opened and that an appropriate 2D coordinate system has already been established.

// draw several isolated points


GLfloat pt[2] = {3.0, 4.0};
glBegin(GL_POINTS);
glVertex2f(1.0, 2.0); // x=1, y=2
glVertex2f(2.0, 3.0); // x=2, y=3
glVertex2fv(pt); // x=3, y=4
glVertex2i(4,5); // x=4, y=5
glEnd();

The various forms of glVertex function calls are defined as follows:


Fig Various forms of GL vertex
The following code fragment specifies a 3D polygon to be drawn, in this case a simple square.
Note that in this case the same square could have been drawn using the GL_QUADS and
GL_QUAD_STRIP primitives.
GLfloat p1[3] = {0,0,1};
GLfloat p2[3] = {1,0,1};
GLfloat p3[3] = {1,1,1};
GLfloat p4[3] = {0,1,1};
glBegin(GL_POLYGON);
glVertex3fv(p1);
glVertex3fv(p2);
glVertex3fv(p3);
glVertex3fv(p4);
glEnd();

Assigning Colours
OpenGL maintains a current drawing colour as part of its state information.
The glColor() function calls are used to change the current drawing colour. assigned using the
glColor function call. Like glVertex(), this function exists in various instantiations. Colour
components are specified in the order of red, green, blue. Colour component values are in the
range [0...1], where 1 corresponds to maximum intensity. For unsigned bytes, the range
corresponds to [0...255]. All primitives following the fragment of code given below would be
drawn in green, assuming no additional glColor() function calls are used.
GLfloat mycolour[3] = {0,0,1}; // blue
glColor3fv( mycolour ); // blue using vector of floats
glColor3f(1.0, 0.0, 0.0); // red using floats
glColor3ub(0,255,0); // green using unsigned bytes
If desired, a polygon can be smoothly shaded to interpolate colours between vertices. This is
accomplished by using the GL_SMOOTH shading mode (the OpenGL default) and by
assigning a desired colour to each vertex, as shown in the following example.
glShadeModel(GL_SMOOTH); // as opposed to GL_FLAT
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0); // red
glVertex3f(0.0, 0.0, 0.0);
glColor3f(0.0, 1.0, 0.0); // green
glVertex3f(1.0, 0.0, 0.0);
glColor3f(0.0, 0.0, 1.0); // blue
glVertex3f(1.0, 1.0, 0.0);
glEnd();
A fourth value called alpha is often appended to the colour vector. This can be used assign a
desired level of transparency to a primitive and finds uses in compositing multiple images
together. An alpha value of 0.0 defines an opaque colour, while an alpha value of 1.0
corresponds to complete transparency.
The screen can be cleared to a particular colour as follows:
glClearcolor(1.0, 1.0, 1.0, 0.0); // sets the clear colour to white and opaque
glClear( GL_COLOR_BUFFER_BIT); // clears the colour frame buffer

Scan conversion: Line drawing algorithms: Digital Differential Analyzer


(DDA) :
Line connects two points. It is a basic element in graphics. To draw a line, you need two
points between which you can draw a line. In the following three algorithms, we refer the
one point of line as X0, Y0 and the second point of line as X1, Y1.
Digital Differential Analyzer (DDA) algorithm is the simple line generation
algorithm which is explained step by step here.
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, you need to identify the number of
steps to put pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y
coordinate. if(absolute(dx) > absolute(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=0; v < Steps; v++) { x = x + Xincrement y = y +
Yincrement; putpixel(Round(x), Round(y)); }
Advantages of DDA Algorithm
1. It is the simplest algorithm and it does not require special skills for implementation.
2. 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 intermediate 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.

Program for DDA Line Drawing Algorithm in C++


#include <graphics.h>
#include <iostream.h>
#include <math.h>
#include <dos.h>

void main( )
{
float x,y,x1,y1,x2,y2,dx,dy,step;
int i,gd=DETECT,gm;

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

cout<<"Enter the value of x1 and y1 : ";


cin>>x1>>y1;
cout<<"Enter the value of x2 and y2: ";
cin>>x2>>y2;

dx=abs(x2-x1);
dy=abs(y2-y1);

if(dx>=dy)
step=dx;
else
step=dy;

dx=dx/step;
dy=dy/step;

x=x1;
y=y1;

i=1;
while(i<=step)
{
putpixel(x,y,5);
x=x+dx;
y=y+dy;
i=i+1;
delay(100);
}

closegraph();
}

Bresenham’s Line Generation Alogorithm :


The Bresenham algorithm is another incremental scan conversion algorithm. The big
advantage of this algorithm is that, it uses only integer calculations. Moving across the x
axis in unit intervals and at each step choose between two different y coordinates
. For example, as shown in the following illustration, from position (2, 3) you need
to choose between (3, 3) and (3, 4). You would like the point that is closer to the
original line.

Fig Bresenham’s Line Generation Alogorithm


At sample position xk+1, the vertical separations from the mathematical line are
labelled as dupper and dlower.

From the above illustration, the y coordinate on the mathematical line at xk+1 is:
𝑌=(𝑋𝑘+1)+𝑏
So, dupper and dlower are given as follows: 𝑑𝑙𝑜𝑤𝑒𝑟 =𝑦−𝑦𝑘
= (𝑋𝑘+1)+𝑏− 𝑌𝑘

and
𝑑𝑢𝑝𝑝𝑒𝑟 =(𝑦𝑘+1)−𝑦
= 𝑌𝑘+1−(𝑋𝑘+1)−𝑏
You can use these to make a simple decision about which pixel is closer to the mathematical
line. This simple decision is based on the difference between the two pixel positions.
𝑑𝑙𝑜𝑤𝑒𝑟− 𝑑𝑢𝑝𝑝𝑒𝑟 =2(𝑥𝑘+1)−2𝑦𝑘+2𝑏−1
Let us substitute m with dy/dx where dx and dy are the differences between the end-points.
(𝑑𝑙𝑜𝑤𝑒𝑟− 𝑑𝑢𝑝𝑝𝑒𝑟) =𝑑𝑥(2𝑑𝑦𝑑𝑥(𝑥𝑘+1)−2𝑦𝑘+2𝑏−1)
=2𝑑𝑦∙𝑥𝑘 −2𝑑𝑥∙𝑦𝑘+2𝑑𝑦+(2𝑏−1) =2𝑑𝑦∙𝑥𝑘 −2𝑑𝑥∙𝑦𝑘+𝐶
So, a decision parameter pk for the kth step along a line is given by
: 𝑝𝑘=𝑑𝑥(𝑑𝑙𝑜𝑤𝑒𝑟− 𝑑𝑢𝑝𝑝𝑒𝑟)
=2𝑑𝑦∙𝑥𝑘 −2𝑑𝑥∙𝑦𝑘+𝐶
The sign of the decision parameter pk is the same as that of dlower – dupper.
If pk is negative, then choose the lower pixel, otherwise choose the upper pixel.
Remember, the coordinate changes occur along the x axis in unit steps, so you can do
everything with integer calculations. At step k+1, the decision parameter is given as:
𝑝𝑘+1=2𝑑𝑦∙𝑥𝑘+1 −2𝑑𝑥∙𝑦𝑘+1+𝐶
Subtracting pk from this we get: 𝑝𝑘+1−𝑝𝑘 =2(𝑥𝑘+1−𝑥𝑘) −2𝑑𝑥(𝑦𝑘+1−𝑦𝑘)
But, xk+1 is the same as xk+1. So: 𝑝𝑘+1=𝑝𝑘+ 2𝑑𝑦−2(𝑦𝑘+1−𝑦𝑘)
Where, yk+1 – yk is either 0 or 1 depending on the sign of pk.
The first decision parameter p0 is evaluated at (x0, y0) is given as: 𝑝0=2𝑑𝑦−𝑑𝑥
Now, keeping in mind all the above points and calculations,
here is the Bresenham algorithm for slope m < 1:

Step 1: Input the two end-points of line, storing the left end-point in (x0, y0).
Step 2: Plot the point (x0, y0).
Step 3: Calculate the constants dx, dy, 2dy, and (2dy – 2dx)
and get the first value for the decision parameter as: 𝑝0=2𝑑𝑦−𝑑𝑥
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
𝑝𝑘+1=𝑝𝑘+2𝑑𝑦
Otherwise, the next point to plot is (xk+1, yk+1) and 𝑝𝑘+1=𝑝𝑘+2𝑑𝑦−2𝑑𝑥
Step 5: Repeat step 4 (dx – 1) times.
For m > 1, find out whether you need to increment x while incrementing y each time. After
solving, the equation for decision parameter pk will be very similar, just the x and y in the
equation gets interchanged.
Advantages of Bresenham Line Drawing Algorithm-
The advantages of Bresenham Line Drawing Algorithm are-
 It is easy to implement.
 It is fast and incremental.
 It executes fast but less faster than DDA Algorithm.
 The points generated by this algorithm are more accurate than DDA
Algorithm.
 It uses fixed points only.

Disadvantages of Bresenham Line Drawing Algorithm-


The disadvantages of Bresenham Line Drawing Algorithm are-
 Though it improves the accuracy of generated points but still the resulted line is not
smooth.
 This algorithm is for the basic line drawing.
 It can not handle diminishing jaggies.

Program for Bresenham’s Line Drawing Algorithm in C++


#include<iostream.h>
#include<graphics.h>

void drawline(int x0, int y0, int x1, int y1)


{
int dx, dy, p, x, y;

dx=x1-x0;
dy=y1-y0;

x=x0;
y=y0;

p=2*dy-dx;

while(x<x1)
{
if(p>=0)
{
putpixel(x,y,7);
y=y+1;
p=p+2*dy-2*dx;
}
else
{
putpixel(x,y,7);
p=p+2*dy;
}
x=x+1;
}
}

int main()
{
int gdriver=DETECT, gmode, error, x0, y0, x1, y1;
initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

cout<<"Enter co-ordinates of first point: ";


cin>>x0>>y0;

cout<<"Enter co-ordinates of second point: ";


cin>>x1>>y1;
drawline(x0, y0, x1, y1);

return 0;
}

Circle drawing algorithms: DDA, Bresenham, and Midpoint.

1.DDA
Draws a circle using DDA Algorithm. Takes the circle parameters (centre and radius)from the
user to plot the desired circle.The program calculates each successive pixel that lies on the
circle using DDA Algorithm.
Program
#include<iostream.h>
#include<conio.h>
#include<dos.h>
#include<math.h>
#include<graphics.h>

//function prototype for DDA circle function


void dda_circle(int xc,int yc,int r);

int main()
{

int xc,yc,r,gd,gm;

clrscr();

//taking circle parameters from the user


cout<<"\nEnter the Center point (xc,yc) :";
cin>>xc>>yc;

cout<<"\nEnter the Radius :";


cin>>r;

detectgraph(&gd,&gm);
initgraph(&gd,&gm,"C:\\turboc3\\bgi");

setcolor(10);
//drawing the co-ordinate axes
line(0,240,640,240);
line(320,0,320,480);

setcolor(5);

//converting the screen co-ordinates to more user friendly co-ordinates


// with respect to the centre of the screen.
xc = 320 + xc;
yc = 240 - yc;

//function call for DDA circle.


dda_circle(xc,yc,r);

getch();
return 0;

/*
Function Definition for DDA circle

Function: dda_circle() Draws the circle with given parameters using DDA algorithm.
Input: Takes three input
1) x co-ordinate for centre
2) y co-ordinate for centre
3) radius of the circle

Return : This function does not return anything.

*/
void dda_circle(int xc,int yc,int r)
{

float xc1,xc2,yc1,yc2,eps,sx,sy;

int val,i;

xc1=r;

yc1=0;

sx=xc1;

sy=yc1;

i=0;

do{

val=pow(2,i);

i++;

}while(val<r);

eps = 1/pow(2,i-1);

do{

xc2 = xc1 + yc1*eps;


yc2 = yc1 - eps*xc2;

putpixel(xc+xc2,yc-yc2,3);
xc1=xc2;

yc1=yc2;

}while((yc1-sy)<eps || (sx-xc1)>eps);

Bresenham’s circle drawing algorithm


It is not easy to display a continuous smooth arc on the computer screen as our computer screen
is made of pixels organized in matrix form. So, to draw a circle on a computer screen we should
always choose the nearest pixels from a printed pixel so as they could form an arc. or whole 360
degree of circle we will divide it in 8-parts each octant of 45 degree. In order to that we will use
Bresenham’s Circle Algorithm for calculation of the locations of the pixels in the first octant of
45 degrees. It assumes that the circle is centered on the origin. So for every pixel (x, y) it
alculates, we draw a pixel in each of the 8 octants of the circle as shown below :

Now, we will see how to calculate the next pixel location from a previously known pixel
location (x, y). In Bresenham’s algorithm at any point (x, y) we have two option either to
choose the next pixel in the east i.e. (x+1, y) or in the south east i.e. (x+1, y-1).

And this can be decided by using the decision parameter d as:


 If d > 0, then (x+1, y-1) is to be chosen as the next pixel as it will be closer to the arc.
 else (x+1, y) is to be chosen as next pixel.
Now to draw the circle for a given radius ‘r’ and centre (xc, yc) We will start from (0, r) and
move in first quadrant till x=y (i.e. 45 degree). We should start from listed initial condition:
d = 3 - (2 * r)
x=0
y=r
Now for each pixel, we will do the following operations:
 Set initial values of (xc, yc) and (x, y)
 Set decision parameter d to d = 3 – (2 * r).
 call drawCircle(int xc, int yc, int x, int y) function.
 Repeat steps 5 to 8 until x < = y
 Increment value of x.
 If d < 0, set d = d + (4*x) + 6
 Else, set d = d + 4 * (x – y) + 10 and decrement y by 1.
 call drawCircle(int xc, int yc, int x, int y) function
// function to draw all other 7 pixels
// present at symmetric position
drawCircle(int xc, int yc, int x, int y)
{
putpixel(xc+x, yc+y, RED);
putpixel(xc-x, yc+y, RED);
putpixel(xc+x, yc-y, RED);
putpixel(xc-x, yc-y, RED);
putpixel(xc+y, yc+x, RED);
putpixel(xc-y, yc+x, RED);
putpixel(xc+y, yc-x, RED);
putpixel(xc-y, yc-x, RED);
}
// C-program for circle drawing
// using Bresenham’s Algorithm
// in computer-graphics
#include <stdio.h>
#include <dos.h>
#include <graphics.h>

// Function to put pixels


// at subsequence points
void drawCircle(int xc, int yc, int x, int y)
{
putpixel(xc+x, yc+y, RED);
putpixel(xc-x, yc+y, RED);
putpixel(xc+x, yc-y, RED);
putpixel(xc-x, yc-y, RED);
putpixel(xc+y, yc+x, RED);
putpixel(xc-y, yc+x, RED);
putpixel(xc+y, yc-x, RED);
putpixel(xc-y, yc-x, RED);
}
// Function for circle-generation
// using Bresenham's algorithm
void circleBres(int xc, int yc, int r)
{
int x = 0, y = r;
int d = 3 - 2 * r;
drawCircle(xc, yc, x, y);
while (y >= x)
{
// for each pixel we will
// draw all eight pixels

x++;

// check for decision parameter


// and correspondingly
// update d, x, y
if (d > 0)
{
y--;
d = d + 4 * (x - y) + 10;
}
else
d = d + 4 * x + 6;
drawCircle(xc, yc, x, y);
delay(50);
}
}

// driver function
int main()
{
int xc = 50, yc = 50, r2 = 30;
int gd = DETECT, gm;
initgraph(&gd, &gm, ""); // initialize graph
circleBres(xc, yc, r); // function call
return 0;
}
Advantages
 It is simple algorithm.
 It can be implement easily
 It is totally based on the equation of circle i.e. x2 +Y2 =R2

Disadvantages
 There is the problem of accuracy while generating points.
 This algorithm is not suitable for the complex and high graphic images..
 Like Mid Point Algorithm, accuracy of the generating points is an issue in this
algorithm.
 This algorithm suffers when used to generate complex and high graphical images.
 There is no significant enhancement with respect to performance.

Program for Midpoint Circle Algorithm in C++

Mid Point Algorithm


Step 1: Input radius r and circle center (xc, yc) and obtain the first point on the
circumference of the circle centered on the origin as
(x0, y0) = (0, r)
Step 2: Calculate the initial value of decision parameter as
P0 = 5/4 – r (See the following description for simplification of this equation.)
f(x, y) = x2 + y2 - r2 = 0
f(xi - 1/2 + e, yi + 1)
= (xi - 1/2 + e)2 + (yi + 1)2 - r2
= (xi- 1/2)2 + (yi + 1)2 - r2 + 2(xi - 1/2)e + e2
= f(xi - 1/2, yi + 1) + 2(xi - 1/2)e + e2 = 0
Let di = f(xi - 1/2, yi + 1) = -2(xi - 1/2)e - e2
Thus,
If e < 0 then di > 0 so choose point S = (xi - 1, yi + 1).
di+1 = f(xi – 1 - 1/2, yi + 1 + 1) = ((xi - 1/2) - 1)2 + ((yi + 1) + 1)2 - r2
= di - 2(xi - 1) + 2(yi + 1) + 1
= di + 2(yi+1 - xi+1) + 1
If e >= 0 then di <= 0 so choose point T = (xi, yi + 1)
di+1 = f(xi - 1/2, yi + 1 + 1)
= di + 2yi+1 + 1
The initial value of di is
d0 = f(r - 1/2, 0 + 1) = (r - 1/2)2 + 12 - r2
= 5/4 - r {1 - r can be used if r is an integer}
When point S = (xi - 1, yi + 1) is chosen, then
di+1 = di + 2xi+1 + 2yi+1 + 1
When point T = (xi, yi + 1) is chosen then
di+1 = di + 2yi+1 + 1
Step 3:
At each XK position starting at K=0, perform the following test:
If PK < 0 then next point on circle (0,0) is (XK+1,YK) and
PK+1 = PK + 2XK+1 + 1
Else
PK+1 = PK + 2XK+1 + 1 – 2YK+1
Where, 2XK+1 = 2XK+2 and 2YK+1 = 2YK-2.
Step 4:
Determine the symmetry points in other seven octants.
Step 5:
Move each calculate pixel position (X, Y) onto the circular path centered on (XC,
YC) and plot the coordinate values.
X = X + XC, Y = Y + YC
Step 6:
Repeat step-3 through 5 until X >= Y.

#include<iostream.h>
#include<graphics.h>

void drawcircle(int x0, int y0, int radius)


{
int x = radius;
int y = 0;
int err = 0;

while (x >= y)
{
putpixel(x0 + x, y0 + y, 7);
putpixel(x0 + y, y0 + x, 7);
putpixel(x0 - y, y0 + x, 7);
putpixel(x0 - x, y0 + y, 7);
putpixel(x0 - x, y0 - y, 7);
putpixel(x0 - y, y0 - x, 7);
putpixel(x0 + y, y0 - x, 7);
putpixel(x0 + x, y0 - y, 7);
if (err <= 0)
{
y += 1;
err += 2*y + 1;
}

if (err > 0)
{
x -= 1;
err -= 2*x + 1;
}
}
}

int main()
{
int gdriver=DETECT, gmode, error, x, y, r;
initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

cout<<"Enter radius of circle: ";


cin>>r;

cout<<"Enter co-ordinates of center(x and y): ";


cin>>x>>y;
drawcircle(x, y, r);

return 0;
}
Output

You might also like