You are on page 1of 59

COMPUTER GRAPHICS

(MC - 318)
(LAB FILE)

Name: MUSKAN GUPTA


Roll No: 2K17/EE/130
Batch: EE
INDEX

1) Develop the DDA Line Drawing Algorithm


2) Develop the Bresenham’s Line Drawing Algorithm
3) Develop the Bresenham’s Circle Drawing Algorithm
4) Develop the Bresenham’s Ellipse Drawing Algorithm
5) Develop the following polygon fill algorithm :
a) Boundary Fill
b) Flood Fill
6) Perform the following 2D Transformation Operation :
a) Translation
b) Rotation
c) Scaling
d) Sheering
7) Perform the following Polygon Clipping Algorithm :
a) Sutherland Method
b) Wailer – Atherton Method
EXPERIMENT - 1

Aim:
Develop the DDA Line Drawing Algorithm

Theory:

Line:

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

There are three-line drawing algorithms:


• DDA
• Bresenham’s
• Mid-Point
Where,
We refer the one point of line as X0, Y0 and the second point of line as X1, Y1.
The lines appear continuous but they are actually made of pixels. The lines are
drawn by a process known as rasterization.

Some terms associated with line generation:


Rasterization: Process of determining which pixels provide the best
approximation to a desired line on the screen.
Scan Conversion: Combination of rasterization and generating the picture in scan
line order. Following is the explanation of DDA algorithm.

DDA Algorithm (Digital Differential Analyzer):


DDA was a mechanical device for numerical solution of differential equations-
Let us assume a line y=mx+h
 dy/dx=m=(y2-y2)/(x2-x1)

The solution of the finite difference approximation is:


Xi+1=Xi+x
Yi+1=Yi+delta_y*(y2-y1)/(x2-x1)

DDA line generation algorithm uses repeated addition.


DDA line generation 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 pixels.
If dx>dy:
then you 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
X_inc=dx/(float)steps
Y_inc=dy/(float)steps
Step 5 – Put the pixel by successfully incrementing x and y coordinates
accordingly and compete the drawing of the line.
Flowchart
Code:

#include <graphics.h>
#include <iostream>
#include <math.h>
#include <dos.h>
using namespace std;
int main( )
{
float x,y,x1,y1,x2,y2,dx,dy,steps;
int m;

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


cin>>x1>>y1;
cout<<"Enter the value of x2 and y2: ";
cin>>x2>>y2;
initwindow(800,800);

dx=abs(x2-x1);
dy=abs(y2-y1);
steps= max(dx,dy);
dx=dx/steps;
dy=dy/steps;
x=x1; y=y1;

i=m;
while(i<=steps)
{
putpixel(x,y,5);
x += dx;
y += dy;
m++;
delay(10);
}
getch();
closegraph();
return 0;
}
Output:

Conclusion :
1. With this experiment we got to learn about DDA’s line
generation algorithm.
2. A C++ program was implemented which generated the line as expected.
3. We also got to know about the advantages and drawbacks of this algorithm.
4. 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.
5. Floor integer values are used in place of normal integer values which may
give different results.
EXPERIMENT - 2

Aim:
Develop the Bresenham’s Line Drawing Algorithm

Theory:

Line:

A 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.
There are three-line drawing algorithms:
• DDA
• Bresenham’s
• Mid-Point
Where,
We refer the one point of line as X0, Y0 and the second point of line as X1, Y1.
The lines appear continuous but they are actually made of pixels. The lines are
drawn by a process known as rasterization.

Bresenham Algorithm:

Bresenham’s line algorithm that determines the points of an n-dimensional raster


that should be selected in order to form a close approximation to a straight line
between two points.it is commonly used to draw line primitives in a bitmap image
(e.g, on computer screen), as it uses only integer addition, subtraction & bit
shifting, all of which are very cheap operations in standard computer
architectures. It is an incremental error algorithm. It is one of the earliest
algorithms developed in the field of computer graphics.

Bresenham’s algorithm chooses the integer Y corresponding to the pixel center


that is closest to the ideal(fraction) Y for the same X; on successive columns Y can
remain the same or increase by 1. The general equation of the line through the
endpoints is given by:

(Y - Y0) /( Y1 - Y0) = (X - X0) /( X1 - X0)


Since we know the column, X, the pixel’s row, Y, is given by rounding this quantity
to the nearest integer:

y= (y1-y0)*(x-x0)/(x1-x0) + y0
The slope △Y/△X depends on the endpoint coordinates only & can
be precomputed , & the ideal Y for successive integer values of X can be
computed starting from & repeatedly adding the slope.

In practice, the algorithm does not keep track of the Y coordinate, which
increases by m = △Y/△X each time increases by one; it keeps an error bound at
each stage, which represents the negative of the distance from (a) the point
where the line exits the pixel to (b) the top edge of the pixel. This value is first set
to m-0.5 (due to using the pixel’s center coordinates),and is incremented by m
each time the x co-ordinate is incremented by one.

If error becomes greater than 0.5 we know that the line has moved upwards one
pixel, and that we must increment our y coordinate and readjust the error to
represent the distance from the top of the new pixel - which is done by
subtracting one from error.

Pseudocode :
plotline(x0,y0,x1,y1)

dx=x1-x0
dy=y1-y0

D=2*dy-dx
y=y0;

For x from x0 to x1

plot(x,y)
if(D>0)
y=y+1 D=D-
2*dx

End if (D=D+2*dy)
FLOWCHART :
CODE :
#include <iostream>
#include <graphics.h>
#include <math.h>
#include <dos.h>
using namespace std;
int main()
{
int x0, y0, x1, y1;
cout<<"Enter co-ordinates of first point:
"; cin>>x0>>y0;
cout<<"Enter co-ordinates of second point:
"; cin>>x1>>y1;

initwindow(800,800);
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;

}
delay(10);
x=x+1;
}
getch();
return 0;
}

OUTPUT :

Conclusion
1. With this experiment we got to learn about Bresenham’s line
generation algorithm.
2. A C++ program was implemented which generated the line as expected.
3. We also got to know about the advantages and drawbacks of this algorithm.
4. It doesn’t have rounding and floating point operations.
5. The main advantage of Bresenham algorithm is its speed. The disadvantage
of such a simple algorithm is that it is meant for basic line drawing. The
“advanced” topic of anti-aliasing is not a part of Bresenham algorithm, so to
draw smooth lines you’d want to use a different algorithm.
EXPERIMENT-3

Aim:
Develop the Bresenham’s Circle Drawing Algorithm

Theory:
A circle is a symmetrical figure any circle-generating algorithm can take advantage of
the circle symmetric to plot right points for each value that the algorithm
calculate Eight-way symmetry is used by reflecting each calculate point around each
45-degree axis. For example, if we calculate one point seven more points could be
found by reflection.

The eight points are :

P1 = (x,y)
P2 = (y.x)
P3 = (-y,x)

P4 = (-x, y)
P5 = (-x, -y)
P6 = (-y,x)
P7 = (y,-x)
P8 = (x,-y)

Equation of circle :
x2 + y2= a2

We consider a circle in second octant from x = 0 to x y. We use the same concept of


eight-way symmetry to plot the entire circle
Principle: We have 2 pixels -
Upper-pixel (U) = (xi + 1 ,yi)
Lower-pixel (L) = (xi+1 , yi - 1)

We need to select, which of these pixels is closer to the true circle and is this algorithm
we find the midpoint between the two pixels. This mid-point, M is given as follows -
M(xi+1 , (yi+yi-1)/2)

l.e., the midpoint of L and U


Now, it depends on the midpoint, which pixel to select Like,

Midpoint is Plot
On the circle Ether U or L pixel

Outside the circle Plot U


Inside the circle Plot L

Where U and L are the Upper and Lower pixel respectively To apply the midpoint
method, we define a circle function –

F(x,y) x2+ y2-12= d


Any point (xy) on the boundary of the circle with radius r satisfies the equation F(x )=0

If d = 0, point (x y) lies on the circle If d > 0, point (x,y) lies outside circle If d < 0,
point (x,y) lies inside circle

Algorithm :
Step1: Start Algorithm

Step2: Declare p, q, x, y, r, d variables


p, q are coordinates of the center of the circle
r is the radius of the circle

Step3: Enter the value of r

Step4: Calculate d = 3 - 2r

Step5: Initialize x=0 &nbsy= r

Step6: Check if the whole circle is scan converted


If x > = y
Stop

Step7: Plot eight points by using concepts of eight-way symmetry. The center is at (p, q).
Current active pixel is (x, y).
putpixel (x+p, y+q)
putpixel (y+p, x+q)
putpixel (-y+p, x+q)
putpixel (-x+p, y+q)
putpixel (-x+p, -y+q)
putpixel (-y+p, -x+q)
putpixel (y+p, -x+q)
putpixel (x+p, -y-q)

Step8: Find location of next pixels to be scanned


If d < 0
then d = d + 4x + 6
increment x = x + 1
If d ≥ 0
then d = d + 4 (x - y) + 10
increment x = x + 1
decrement y = y - 1

Step9: Go to step 6

Step10: Stop

Flowchart:
Code:
#include
<graphics.h>
#include <iostream>
#include <math.h>
using namespace
std;

int main()
{
float xc, yc,r;
cout<<”Enter centre points x and y :”;
cin>>xc>>yc;
cout<<”Enter radius of circle
:”; cin>>r;
initwindow(600,600);
float x=0, y=r;
float p=1-
y;
while(x<=y
)
{
putpixel(xc+x, yc+y, 5);
putpixel(xc-x, yc-y, 5);
putpixel(xc+x, yc-y, 5);
putpixel(xc-x, yc+y, 5);
putpixel(xc+y, yc+x, 5);
putpixel(xc-y, yc-x, 5);
putpixel(xc+y, yc-x, 5);
putpixel(xc-y, yc+x,
5); delay(10);
if(p>=0)
{
p += 2*x – 2*y + 5; y--;

}
else
{ p += 2*x+3;

}
x
+
+
;
}
getch();
retur
n 0;
}

Output:

Conclusion:
We have successfully implemented the Midpoint circle algorithm by writing a
C++ program. Through the course of the implementation, we observed and
learnt various pros and cons of using the Midpoint circle algorithm. They are as
follows:
1. The midpoint method is used for deriving efficient scan-conversion
algorithms to draw geometric curves on raster displays
2. The method is general and is used to transform the nonparametric
equation f(x,y) = 0, which describes the curve, into an algorithms that
draws the curve.
3. This method is very time consuming.
4. The distance between the pixels is not equal so we won't get smooth
circle.

EXPERIMENT-4

Aim:
Develop the Bresenham’s Ellipse Drawing Algorithm
Theory
Midpoint ellipse algorithm is a method for drawing ellipses in computer graphics. This
method is modified from Bresenham’s algorithm so it is sometimes known as
Bresenham's circle algorithm.

The advantage of this modified method is that only addition operations are required
in the program loops. This leads to simple and fast implementation in all processors.
Let us consider one quarter of an ellipse. The curve is divided into two regions. In
region I, the slope on the curve is greater than –1 while in region II less than –1.

Consider the general equation of an ellipse,


b2 x2 + a2 y2 – a2 b2 = 0
where a is the horizontal radius and b is the vertical radius, we can define an
function f(x,y) by which the error due to a prediction coordinate (x,y) can be
obtained. The appropriate pixels can be selected according to the error so that the
required ellipse is formed. The error can be confined within half a pixel.
Set f(x,y) = b2 x2 + a2 y2 – a2
b2 In region I (dy/dx > –1),
x is always incremented in each step, i.e. xk+1 = xk + 1. yk+1 = yk if E is selected,
or yk+1 = yk – 1 if SE is selected.
In order to make decision between S and SE, a prediction (xk+1, yk–½) is set at the
middle between the two candidate pixels. A prediction function Pk can be defined as
follows:

Pk = f(xk+1, yk–½)
= b2 (xk+1)2 + a2 (yk–½)2 – a2 b2
= b2 (xk 2 + 2xk + 1) + a2 (yk 2 – yk + ¼) – a2
b2 If Pk < 0, select E :
Pk+1 E= f(xk+2, yk–½)
= b2 (xk+2)2 + a2 (yk–½)2 – a2 b2
= b2 (xk 2 + 4xk + 4) + a2 (yk 2 – yk + ¼) – a2 b2
Change of Pk E is: ∆Pk E = Pk+1 E – Pk = b2 (2xk + 3)
If Pk > 0, select SE :
Pk+1 SE = f(xk+2, yk–3/2)
= b2 (xk+2)2 + a2 (yk–3/2)2 – a2 b2
= b2 (xk 2 + 4xk + 4) + a2 (yk 2 – 3yk + 9/4) – a2
b2 Change of Pk SE is
∆Pk SE = Pk+1 SE – Pk
= b2 (2xk + 3) – 2a2 (yk
– 1) Calculate the changes of ∆
Pk:
If E is selected,
∆Pk+1 E = b2 (2xk + 5)
∆^2 Pk E = ∆Pk+1 E – ∆Pk E = 2b^2
∆Pk+1 SE = b2 (2xk + 5) – 2a2 (yk – 1)
∆^2 Pk SE = ∆Pk+1 SE – ∆Pk SE = 2b^2 If SE is selected,
∆Pk+1 E = b^2 (2xk + 5)
∆^2 Pk E = ∆Pk+1 E – ∆Pk E = 2b^2
∆Pk+1 SE = b^2 (2xk + 5) – 2a^2 (yk – 2)
∆^2 Pk SE = ∆Pk+1 SE – ∆Pk SE = 2(a^2 + b^2 )

Initial Values:
x0 = 0, y0 = b, P0 = b2 + ¼a2 (1 – 4b)
∆P0 E = 3b^2 , ∆P0 SE = 3b^2 – 2a^2 (b – 1)
In region II (dy/dx < –1), all calculations are similar to that in region I except that y is
decremented in each step.

y is always decremented in each step, i.e. yk+1 = yk –


1. xk+1 = xk if S is selected, or xk+1 = xk + 1 if SE is
selected. Pk = f(xk+½, yk–1)
= b^2 (xk+½)2 + a^2 (yk–1)^2 – a^2 b^2
= b^2 (xk^2 + xk + ¼) + a^2 (yk^2 – 2yk + 1) – a^2
b^2 If Pk > 0, select S :
Pk+1 S= f(xk+½, yk–2)
= b^2 (xk+½)^2 + a^2 (yk–2)^2 – a^2 b^2
= b^2 (xk^2 + xk + ¼) + a^2 (yk^2 – 4yk + 4) – a^2
b^2 Change of Pk S is: ∆Pk^S = Pk+1^S – Pk = a^2 (3 –
2yk)
If Pk < 0, select SE :
Pk+1^SE = f(xk+3/2, yk–2)
= b^2 (xk+3/2)^2 + a^2 (yk–2)^2 – a^2 b^2
= b2 (xk^2 + 3xk + 9/4) + a^2 (yk^2 – 4yk + 4) – a^2 b^2 Change of Pk SE is
∆Pk SE = Pk+1 SE – Pk = 2b^2 (xk + 1) + a^2 (3 –
2yk) Calculate the changes of ∆Pk:

If S is selected,
∆Pk+1 S = a^2 (5 – 2yk)
∆^2 Pk S = ∆Pk+1 S – ∆Pk S
= 2a^2 ∆Pk+1 SE
= 2b^2 (xk + 1) + a^2 (5 – 2yk)
∆2 Pk SE = ∆Pk+1 SE – ∆Pk SE = 2a^2 If SE is selected,
∆Pk+1 S = a^2 (5 – 2yk)
∆^2 Pk S = ∆Pk+1 S – ∆Pk S = 2a^2
∆Pk+1 SE = 2b^2 (2xk + 2) – a^2 (5 – 2yk)
∆^2 Pk SE = ∆Pk+1 SE – ∆Pk SE = 2(a^2 + b^2 ) Determine the boundary between region I
and II: Set f(x, y) = 0, dy/dx = –bx / [a^2 √(1 – x^2 /a^2 )].
When dy/dx = –1, x = a^2 / √(a^2 + b^2 ) and y = b^2 / √(a^2 + b^2 ). At region I, dy/dx >
–1, x < a^2 / √(a^2 + b^2 ) and y > b^2 / √(a^2 + b^2 ), therefore
∆Pk SE < b^2 (2a^2 /√(a^2 + b^2 ) – 2a^2 (b^2 /√(a^2 + b^2 ) – 1) = 2a^2 + 3b^2

Initial values at region II:


x0 = a^2 / √(a^2 + b^2

) y0 = b^2 / √(a^2 +

b^2 )

x0 and y0 will be the accumulative results from region I at the boundary. It is not
necessary to calculate them from values of a and b.
P0 = Pk I – ¼[a^2 (4y0 – 3) + b2 (4x0 + 3)] where Pk I is the accumulative result
from region I at the boundary.
∆P0 E = b^2 (2x0 + 3)
∆P0 SE = 2a^2 + 3b^2

Algorithm:
1. Take input radius along x axis and y axis and obtain centre of ellipse.
2. Initially, we assume ellipse to be centred at origin and the first point as : (x, y0)= (0,
ry).
3. Obtain the initial decision parameter for region 1 as: p10=ry2+1/4rx2-rx 2ry
4. For every xk position in region 1 :
If p1k<0 then the next point along the is (xk+1 , yk) and p1k+1=p1k+2ry2xk+1+ry2
Else, the next point is (xk+1, yk-1 )
And p1k+1=p1k+2ry2xk+1 – 2rx2yk+1+ry2
5. Obtain the initial value in region 2 using the last point (x0, y0) of region 1 as:
p20=ry2(x0+1/2)2+rx2 (y0-1)2-rx2ry2
6. At each yk in region 2 starting at k =0 perform the following task.
If p2k>0 the next point is (xk, yk-1) and p2k+1=p2k-2rx2yk+1+rx2
7. Else, the next point is (xk+1, yk -1) and p2k+1=p2k+2ry2xk+1 -2rx2yk+1+rx2
8. Now obtain the symmetric points in the three quadrants and plot the coordinate
value as: x=x+xc, y=y+yc
9. Repeat the steps for region 1 until 2ry2x&gt=2rx2y
Flowchart:
Code:
#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 coordinates of centre : ";


cin>>x0>>y0;

cout<<"Enter x,y radius of ellipse: ";


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

return 0;
}
Output:

Conclusion :
In this algorithm we first calculate the p1 then we started loop till dx<dy. In this
loop if(p1<0) then x=x+1,dx=dx+r^2y and p1=p1+dx+r^2y else y=y-1,dy=dy-r^2x
and p1=p1+dx-dy+r^2y
Then, for second decision parameter we calculate p2 as p2=(x+1/4)r^2y+r^2x(y-
1)^2- r^2xr^2y
We start a loop till (y>0), if (p2>0) then y=y-1,dy=dy-2r^2x and p2=p2-dy+r^2x
else, x=x+1,y=y-1,dx=dx+2r^2y,dy=dy-2r^2x and p2=p2+dx-dy-r^2x.

 The mid-point method for deriving efficient scan conversion algorithms to


draw geometric curves on raster displays in described. The method is
general and is used to transform the non-parametric equation f(x,y)=0,
which describes the curve, into an algorithm that draws the curve.
 Time consumption is high.
 The distance between the pixels is not equals so we won’t get smooth circle.
EXPERIMENT-5(a)

Aim:
Develop the Boundary fill algorithm

Theory :

Polygon Filling:-

Filling the polygon means highlighting all the pixels which lie inside the polygon with
any colour other than background colour. Polygons are easier to fill since they have
linear boundaries.
There are two basic approaches used to fill the polygon:
a) Boundary Fill Algorithm
b) Flood Fill Algorithm
In this experiment, we will be organizing the Boundary Fill Algorithm

Boundary Fill Algorithm :


In this method, edges of the polygons are drawn. Then starting with some seed, any
point inside the Polygon we examine the neighbouring pixels to check whether the
boundary pixel is reached. If boundary pixels are not reached, pixels are highlighted
and the process is continued until boundary pixels are reached.

Boundary defined regions may be either 4-connected or 8-connected as shown in


the figure (a) and (b).
If a region is 4-connected, then every pixel in the region may be reached by a
combination of moves in only four directions: left, right, up and down.
For an 8-connected region every pixel in the region may be reached by a
combination of moves in the two horizontal, two vertical, and four diagonal
directions.
4-connected pixels : After painting a pixel, the function is called for four
neighbouring points. These are the pixel positions that are right, left, above and
below the current pixel. Areas filled by this method are called 4-connected.
8-connected pixels : More complex figures are filled using this approach. The pixels
to be tested are the 8 neighbouring pixels, the pixel on the right, left, above, below
and the 4 diagonal pixels. Areas filled by this method are called 8-connected.

Algorithm :
The problem is pretty simple and usually follows these steps:

1. Take the position of the starting point and the boundary color.
2. Decide wether you want to go in 4 directions (N, S, W, E) or 8 directions (N, S,
W, E, NW, NE, SW, SE).
3. Choose a fill color.
4. Travel in those directions.
5. If the pixel you land on is not the fill color or the boundary color , replace it with
the fill color.
6. Repeat 4 and 5 until you’ve been everywhere within the boundaries.

Flowchart :
Code : (For 4- connected Neighbours)

#include <graphics.h>

void boundaryFillAlgoFor4(int x, int y, int FillColor,int BoundaryColor)


{
if(getpixel(x, y) != BoundaryColor&& getpixel(x, y) != FillColor)
{
putpixel(x, y, fill_color);
boundaryFillAlgoFor4 (x + 1, y, FillColor, BoundaryColor);
boundaryFillAlgoFor4 (x, y + 1, FillColor, BoundaryColor);
boundaryFillAlgoFor4 (x - 1, y, FillColor, BoundaryColor);
boundaryFillAlgoFor4 (x, y - 1, FillColor, BoundaryColor);
}
}

int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

int x = 250, y = 200, rad= 50;


circle(x, y, rad);

boundaryFillAlgoFor4(x, y, 4, 15);
delay(10000);

getch();
closegraph();

return 0;
}
Output :

Code : (For 8- connected Neighbours)


#include <graphics.h>

// Function for 8 connected Pixels


void boundaryFillAlgoFor8(int x, int y, int FillColor,int BoundaryColor)
{
if(getpixel(x, y) != boundary_color &&
getpixel(x, y) != fill_color)
{
putpixel(x, y, fill_color);
boundaryFillAlgoFor8 (x + 1, y, FillColor, BoundaryColor);
boundaryFillAlgoFor8 (x, y + 1, FillColor, BoundaryColor);
boundaryFillAlgoFor8 (x - 1, y, FillColor, BoundaryColor);
boundaryFillAlgoFor8 (x, y - 1, FillColor, BoundaryColor);
boundaryFillAlgoFor8 (x - 1, y - 1, FillColor, BoundaryColor);
boundaryFillAlgoFor8 (x - 1, y + 1, FillColor, BoundaryColor);
boundaryFillAlgoFor8 (x + 1, y - 1, FillColor, BoundaryColor);
boundaryFillAlgoFor8 (x + 1, y + 1, FillColor, BoundaryColor);
}
}

//driver code
int main()
{
int gd = DETECT, gm;

initgraph(&gd, &gm, "");


rectangle(50, 50, 100, 100);

boundaryFillAlgoFor8 (55, 55, 2, 15);


delay(10000);

getch();
closegraph();

return 0;
}

Output :
Conclusion:

1) Boundary Fill Algorithm is recursive in nature. It takes an interior point(x, y), a fill
color, and a boundary color as the input.
2) The algorithm starts by checking the color of (x, y). If it’s color is not equal to the fill
color and the boundary color, then it is painted with the fill color and the function is
called for all the neighbours of (x, y).
3) If a point is found to be of fill color or of boundary color, the function does not call
its neighbours and returns.
4) This process continues until all points up to the boundary color for the region have
been tested.
EXPERIMENT-5(b)

Aim : Develop the Flood fill algorithm

Theory :
Flood fill algorithm helps in visiting each and every point in a given area. It determines the
area connected to a given cell in a multi-dimensional array. Following are some famous
implementations of flood fill algorithm:

Bucket Fill in Paint:


Clicking in an area with this tool selected fills that area with the selected colour.

Solving a Maze:
Given a matrix with some starting point, and some destination with some obstacles in
between, this algorithm helps to find out the path from source to destination

Minesweeper:
When a blank cell is discovered, this algorithm helps in revealing neighbouring cells. This
step is done recursively till cells having numbers are discovered.

Flood fill algorithm can be simply modelled as graph traversal problem, representing the
given area as a matrix and considering every cell of that matrix as a vertex that is
connected to points above it, below it, to right of it, and to left of it and in case of 8-
connections, to the points at both diagonals also. For example, consider the image given
below.

It clearly shows how the cell in the middle is connected to cells around it. For instance,
there are 8-connections like there are in Minesweeper (clicking on any cell that turns out
to be blank reveals 8 cells around it which contains a number or are blank). The cell (1,1) is
connected to (0,0), (0,1), (0,2), (1,0), (1,2), (2,0), (2,1), (2,2).
In general any cell (x,y) is connected
to (x−1,y−1), (x−1,y), (x−1,y+1), (x,y−1), (x,y+1), (x+1,y−1), (x+1,y), (x+1,y+1). Of course,
the boundary conditions are to be kept in mind.

Now that the given area has been modelled as a graph, a DFS or BFS can be applied to
traverse that graph.

Algorithm :
The problem is pretty simple and usually follows these steps:

1. Take the position of the starting point.


2. Decide wether you want to go in 4 directions (N, S, W, E) or 8 directions (N, S, W, E,
NW, NE, SW, SE).
3. Choose a replacement color and a target color.
4. Travel in those directions.
5. If the tile you land on is a target, reaplce it with the chosen color.
6. Repeat 4 and 5 until you’ve been everywhere within the boundaries.

Code :
#include<conio.h>
#include<graphics.h>
#include<dos.h>
#include<iostream.h>
void floodFill(int x, int y, int old, int fill)
{
int current;
current=getpixel(x,y);

if(current==old)
{
putpixel(x,y,fill);
delay(5);
floodFill(x+1,y,old,fill);
floodFill(x-1,y,old,fill);
floodFill(x, y+1,old,fill);
floodFill(x,y-1,old,fill);
}
}
void main()
{
int x,y,o=0;
clrscr();
int gDriver=DETECT,gmode;
initgraph(&gDriver,&gmode, "C:\\TC\\BGI");

rectangle(100,100,150,200);
x=(100+150)/2;
y=(100+200)/2;

floodFill(x,y,2,4);
getch();

closegraph();
}

Output :

Conclusion :
1) In Flood Fill algorithm we start with some seed and examine the neighboring pixels,
however pixels are checked for a specified interior color instead of boundary color
and is replaced by a new color.

2) It can be done using 4 connected or 8 connected region method.


EXPERIMENT – 6(a)
Aim :
Perform the following 2D Translation Operation

Theory :
In Computer graphics,
2D Translation is a process of moving an object from one position to another in a two
dimensional plane.
Consider a point object O has to be moved from one position to another in a 2D plane.
Let-
 Initial coordinates of the object O = (Xold, Yold)
 New coordinates of the object O after translation = (Xnew, Ynew)
 Translation vector or Shift vector = (Tx, Ty)

Given a Translation vector (Tx, Ty)-


 Tx defines the distance the Xold coordinate has to be moved.
 Ty defines the distance the Yold coordinate has to be moved.
This translation is achieved by adding the translation coordinates to the old coordinates
of the object as-
 Xnew = Xold + Tx (This denotes translation towards X axis)
 Ynew = Yold + Ty (This denotes translation towards Y axis)

In Matrix form, the above translation equations may be represented as-

 The homogeneous coordinates representation of (X, Y) is (X, Y, 1).


 Through this representation, all the transformations can be performed using matrix /
vector multiplications.

Algorithm :

1) Suppose, If point (X, Y) is to be translated by amount Dx and Dy to a new location (X’,


Y’) then new coordinates can be obtained by adding Dx to X and Dy to Y as:
X' = Dx + X
Y' = Dy + Y
or P' = T + P where
P' = (X', Y'),
T = (Dx, Dy ),
P = (X, Y)
2) Here, P(X, Y) is the original point. T(Dx, Dy) is the translation factor, i.e. the amount by
which the point will be translated. P'(X’, Y’) is the coordinates of point P after translation.
Code :
#include<bits/stdc++.h>
#include<graphics.h>

void 2DTranslation( int P[][2], int T[])


{

int gd = DETECT, gm, errorcode;


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

setcolor (2);
line(P[0][0], P[0][1], P[1][0], P[1][1]);

P[0][0] = P[0][0] + T[0];


P[0][1] = P[0][1] + T[1];
P[1][0] = P[1][0] + T[0];
P[1][1] = P[1][1] + T[1];

setcolor(3);
line(P[0][0], P[0][1], P[1][0], P[1][1]);
closegraph();
}

int main()
{
int P[2][2] = {5, 8, 12, 18};
int T[] = {2, 1};
2DTranslation(P, T);
return 0;
}
Output :

Conclusion :

3) A translation moves an object to a different position on the screen. You can


translate a point in 2D by adding translation coordinate (tx, ty) to the original
coordinate X,YX,Y to get the new coordinate Xʹ,YʹXʹ,Yʹ.

4) From the above figure, you can write that −


X’ = X + tx
Y’ = Y + ty
5) The pair (tx, ty) is called the translation vector or shift vector. The above
equations can also be represented using the column vectors.
P=[X][Y]P=[X][Y] p' = [Xʹ][Yʹ][Xʹ][Yʹ]T = [tx][ty][tx][ty]
We can write it as −
P’ = P + T
EXPERIMENT-6(b)

Aim :

Implementation of 2D Rotation

Theory :
In Computer graphics,
2D Rotation is a process of rotating an object with respect to an angle in a two
dimensional plane.
Consider a point object O has to be rotated from one angle to another in a 2D
plane.
Let-
 Initial coordinates of the object O = (Xold, Yold)
 Initial angle of the object O with respect to origin = Φ
 Rotation angle = θ
 New coordinates of the object O after rotation = (Xnew, Ynew)

This rotation is achieved by using the following rotation equations-


 Xnew = Xold x cosθ – Yold x sinθ
 Ynew = Xold x sinθ + Yold x cosθ

In Matrix form, the above rotation equations may be represented as-

For homogeneous coordinates, the above rotation matrix may be represented as


a 3 x 3 matrix as-
Algorithm :

In order to rotate an object we need to rotate each vertex of the figure individually.

Step 1 : On rotating a point P(x, y) by an angle A about the origin we get a point
P'(x’, y’). The values of x’ and y’ can be calculated as follows:-

Step 2 :
We know that,
x = rcosB, y = rsinB
Step 3: Calculate :
x’ = rcos(A+B) = r(cosAcosB – sinAsinB) = rcosBcosA – rsinBsinA = xcosA – ysinA
y’ = rsin(A+B) = r(sinAcosB + cosAsinB) = rcosBsinA + rsinBcosA = xsinA + ycosA

Rotational Matrix Equation:-

 x '   x   cos A  sin A 


 y '   y    sin A cos A 
     

Code :

#include<stdio.h>
#include<graphics.h>
#include<math.h>
int main()
{
int gd=0,gm,x1,y1,x2,y2;
double s,c, angle;
initgraph(&gd, &gm, "C:\\TC\\BGI");
setcolor(RED);

printf("Enter the coordinates of Line: ");


scanf("%d%d%d%d",&x1,&y1,&x2,&y2);

cleardevice();
setbkcolor(WHITE);

line(x1,y1,x2,y2);
getch();

printf("Enter the angle of rotation: ");

scanf("%lf", &angle);
setcolor(6);

c = cos(angle *3.14/180);
s = sin(angle *3.14/180);
x1 = floor(x1 * c + y1 * s);
y1 = floor(-x1 * s + y1 * c);
x2 = floor(x2 * c + y2 * s);
y2 = floor(-x2 * s + y2 * c);
cleardevice();
line(x1, y1 ,x2, y2);
getch();
closegraph();
return 0;
}
Output :

Conclusion :
1) Rotation is one of the important 2d transformations in computer graphics.
2) The program tells how to rotate points or polygon around a point (the pivot point).
3) This program using the graphics library reads the number of sides of polygon, co-
ordinates of its vertices, the pivot point for rotation, and angle of rotation.
4) It displays the original polygon and rotated polygon in different colors in same
screen. More Computer graphics lab problems are available under related posts
heading.
Experiment-6(c)

Aim :
Implementation of 2D Scaling

Theory :
In computer graphics, scaling is a process of modifying or altering the size of objects.
 Scaling may be used to increase or reduce the size of object.
 Scaling subjects the coordinate points of the original object to change.
 Scaling factor determines whether the object size is to be increased or reduced.
 If scaling factor > 1, then the object size is increased.
 If scaling factor < 1, then the object size is reduced.
Consider a point object O has to be scaled in a 2D plane.
Let-
 Initial coordinates of the object O = (Xold, Yold)
 Scaling factor for X-axis = Sx
 Scaling factor for Y-axis = Sy
 New coordinates of the object O after scaling = (Xnew, Ynew)
This scaling is achieved by using the following scaling equations-
 Xnew = Xold x Sx
 Ynew = Yold x Sy

In Matrix form, the above scaling equations may be represented as-

For homogeneous coordinates, the above scaling matrix may be represented as a 3 x


3 matrix as-
Algorithm :
1. Make a 2x2 scaling matrix S as
Sx 0
0 Sy
2. For each point of the polygon.
3. Make a 2x1 matrix P, where P[0][0] equals to x coordinate of the point and P[1][0]
equals to y coordinate of the point.
4. Multiply scaling matrix S with point matrix P to get the new coordinate.
5. Draw the polygon using new coordinates.

Code :

#include<stdio.h>
#include<graphics.h>
#include<math.h>

void scaling(int x1,int y1,int x2,int y2,int x3,int y3)


{
int sx,sy,xn1,yn1,xn2,xn3,yn3,yn2,gd,gm;
printf("enter the scaling vector\n");
scanf("%d %d",&sx,&sy);

xn1=x1*sx;
yn1=y1*sy;
xn2=x2*sx;
yn2=y2*sy;
xn3=x3*sx;
yn3=y3*sy;

initgraph(&gd,&gm,"");

line(x1,y1,x2,y2);
line(x1,y1,x3,y3);
line(x2,y2,x3,y3);
delay(600);

line(xn1,yn1,xn2,yn2);
line(xn1,yn1,xn3,yn3);
line(xn2,yn2,xn3,yn3);
delay(600);
cleardevice();

}
int main()
{
int ch,x1,y1,x2,y2,x3,y3;
printf("enter the vertex co-ordinates of triangle\n");
scanf("%d %d %d %d %d %d",&x1,&y1,&x2,&y2,&x3,&y3);
scaling(x1,y1,x2,y2,x3,y3);
return 0;
}

Output:

Conclusion :
1) A scaling transformation alters size of an object. In the scaling process, we either
compress or expand the dimension of the object.

2) Scaling operation can be achieved by multiplying each vertex coordinate (x, y) of


the polygon by scaling factor sx and sy to produce the transformed coordinates
as (x’, y’).
So, x’ = x * sx and y’ = y * sy.

3) The scaling factor sx, sy scales the object in X and Y direction respectively.
EXPERIMENT-6(d)
Aim:
To implement 2D sheering.

Theory:
In Computer graphics, 2D Shearing is an ideal technique to change the shape of an existing
object in a two dimensional plane.
A transformation that slants the shape of an object is called the shear transformation.
There are two shear transformations X-Shear and Y-Shear. One shifts X coordinates
values and other shifts Y coordinate values. However; in both the cases only one
coordinate changes its coordinates and other preserves its values. Shearing is also
termed as Skewing.
X-Shear
The X-Shear preserves the Y coordinate and changes are made to X coordinates, which
causes the vertical lines to tilt right or left as shown in below figure.

The transformation matrix for X-Shear can be represented as −

Y' = Y + Shy . X
X’ = X
Y-Shear
The Y-Shear preserves the X coordinates and changes the Y coordinates which causes the
horizontal lines to transform into lines which slopes up or down as shown in the
following figure.

The Y-Shear can be represented in matrix from as −

X’ = X + Shx . Y
Y’ = Y
Algorithm :
1. Start
2. Initialize the graphics mode.
3. Construct a 2D object (use Drawpoly()) e.g. (x,y)
4. Shearing
a. X-shear
i. Get the shearing value shx
ii. x’=x + shx * y, y’=y
iii. Plot (x’,y’)
b. Y-shear
i. Get the shearing value shy
ii. x’=x , y’=y+ shy * x
c. Plot (x’,y’)
Code:
#include<iostream.h>
#include<graphics.h>
#include<conio.h>
void main()
{

int x1,y1,x2,y2,s,g,p,q;
float sx,sy;

cout<<“\n\t\t\t\*To show shearing effect on rectangle*\n”;


cout<<“\nenter the x1 and x2 coordinates:-\n”;

cin>>x1>>x2;
cout<<“\nenter the y1 and y2 coordinates:-\n”;

cin>>y1>>y2;
cout<<“\nenter the shearing factor along the x-axis:-“;

cin>>sx;
cout<<“\nenter trhe scaling factor to the y-axis:-“;

cin>>sy;

int gd=DETECT,gm;
initgraph(&gd,&gm,””);
setbkcolor(WHITE);
setcolor(8);

line(x1,y1,x2,y1);
line(x2,y2,x1,y2) ;
line(x2,y1,x2,y2);
line(x1,y2,x1,y1);

s=x1+int((sx*y1)+0.5);
p=y1+int((sy*x1)+0.5);
g=x2+int((sx*y2)+0.5);
q=y2+int((sy*x2)+0.5);

setcolor(8);
line(x1,y1,x2,p);
line(g,q,s,y2) ;
line(x2,p,g,q);
line(s,y2,x1,y1);
setcolor(8);
outtextxy(100,60,”Shearing on rectangle”);
getch();

}
Output :

Conclusion :
1) Shear transformation or shearing is one of the 2d transformations in computer
graphics. Here i present a c program for shear transformation of polygons. The shear
transformation works as follows:

2) For shearing along X axis, shearfactor* (y coordinate) is added with x co-ordinates of all
points. That is:

newx=oldx+shearfactor*oldy

3) Similarly, to shear along Y axis, we add shearfactor* (x coordinate) to y co-ordinates of


all points.

newy=oldy+shearfactor*oldx
EXPERIMENT-7(a)
Aim:
To implement Sutherland method of polygon Clipping.
Theory :

It is performed by processing the boundary of polygon against each window corner or


edge. First of all entire polygon is clipped against one edge, then resulting polygon is
considered, then the polygon is considered against the second edge, so on for all four
edges.

Four possible situations while processing

1. If the first vertex is an outside the window, the second vertex is inside the
window. Then second vertex is added to the output list. The point of
intersection of window boundary and polygon side (edge) is also added to the
output line.
2. If both vertexes are inside window boundary. Then only second vertex is added
to the output list.
3. If the first vertex is inside the window and second is an outside window. The
edge which intersects with window is added to output list.
4. If both vertices are the outside window, then nothing is added to output list.

Algorithm:
Code:

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int gd,gm,n,*x,i,k=0;

wx1=220,wy1=140,wx2=420,wy2=140,wx3=420,wy3=340,wx4=220,wy4=340;

int w[]={220,140,420,140,420,340,220,340,220,140

detectgraph(&gd,&gm);

initgraph(&gd,&gm," C:\\TC\\BGI ");

printf("Window:-");
setcolor(RED);
drawpoly(5,w);

printf("Enter the no. of vertices of polygon: ");

scanf("%d",&n);
x = malloc(n*2+1);
printf("Enter the coordinates of points:\n");

k=0;
for(i=0;i<n*2;i+=2)
{
printf("(x%d,y%d): ",k,k);
scanf("%d,%d",&x[i],&x[i+1]);
k++;
}
x[n*2]=x[0];

drawpoly method.
x[n*2+1]=x[1];
setcolor(WHITE);

drawpoly(n+1,x);
printf("\nPress a button to clip a polygon..");
getch();

setcolor(RED);
drawpoly(5,w);
setfillstyle(SOLID_FILL,BLACK);
floodfill(2,2,RED);

gotoxy(1,1);

printf("\nThis is the clipped polygon..");


getch();

cleardevice();
closegraph();
return 0;
}
Output:
Conclusion:
1) A convex polygon and a convex clipping area are given. The task is to clip polygon
edges using the Sutherland–Hodgman Algorithm.
2) Input is in the form of vertices of the polygon in clockwise order.
3) The edge (of clipping area) is extended infinitely to create a boundary and all the
vertices are clipped using this boundary.
4) The new list of vertices generated is passed to the next edge of the clip polygon in
clockwise fashion until all the edges have been used.
EXPERIMENT-7(b)
Aim:

To Implement Wailer – Atherton Method of polygon clipping.

Theory :
The Weiler–Atherton is a polygon-clipping algorithm. It is used in the areas like
computer graphics, games development and others where clipping of polygon is
needed. It allows clipping of a subject or candidate polygon by an arbitrarily shaped
clipping polygon/area/region.
It is generally applicable only in 2D. However, it can be used in 3D through visible
surface determination and with improved efficiency through Z-ordering
Given polygon A as the clipping region and polygon B as the subject polygon to be
clipped, the algorithm consists of the following steps:

1. List the vertices of the clipping-region polygon A and those of the subject
polygon B.
2. Label the listed vertices of subject polygon B as either inside or outside of
clipping region A.
3. Find all the polygon intersections and insert them into both lists, linking the lists
at the intersections.
4. Generate a list of "inbound" intersections – the intersections where the vector
from the intersection to the subsequent vertex of subject polygon B begins
inside the clipping region.
5. Follow each intersection clockwise around the linked lists until the start position
is found.

Algorithm:
1) In this algorithm we take a starting vertex like I1 and traverse the polygon like I1, V3,
I2.
2) At occurrence of leaving intersection the algorithm follows the clip polygon vertex list
from leaving vertex in downward direction.
3) At occurrence of entering intersection the algorithm follows subject polygon vertex list
from the entering intersection vertex. This process is repeated till we get starting
vertex.
4) This process has to be repeated for all remaining entering intersections which are not
included in the previous traversing of vertex list.
5) Since I3 was not included in first traverse, hence, we start the second traversal from I3.
Therefore, first traversal gives polygon as: I1, V3, I2, I1 and second traversal gives
polygon as: I3, V5, I4, I3.
Code:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>

void clip(float,float,float);
int i,j=0,n;
int rx1,rx2,ry1,ry2;
float x1[8],y1[8];

void main()
{
int gd=DETECT,gm;
int i,n;
float x[8],y[8],m;
clrscr();
initgraph(&gd,&gm,"");
printf("coordinates for rectangle : ");
scanf("%d%d%d%d",&rx1,&ry1,&rx2,&ry2);
printf("no. of sides for polygon : ");
scanf("%d",&n);
printf("coordinates : ");
for(i=0;i<n;i++)
{
scanf("%f%f",&x[i],&y[i]);
}
cleardevice();
outtextxy(10,10,"Before clipping");

rectangle(rx1,ry1,rx2,ry2);
for(i=0;i<n-1;i++)
line(x[i],y[i],x[i+1],y[i+1]);
line(x[i],y[i],x[0],y[0]);
getch();
cleardevice();
for(i=0;i<n-1;i++)
{
m=(y[i+1]-y[i])/(x[i+1]-x[i]);
clip(x[i],y[i],m);
clip(x[i+1],y[i+1],m);
}

m=(y[i]-y[0])/(x[i]-x[0]);
clip(x[i],y[i],m);
clip(x[0],y[0],m);

outtextxy(10,10,"POLYGON AFTER CLIPPING”);

rectangle(rx1,ry1,rx2,ry2);
for(i=0;i<j-1;i++)
line(x1[i],y1[i],x1[i+1],y1[i+1]);
getch();
}

void clip(float e,float f,float m)


{
while(e<rx1 e>rx2 f<ry1 f>ry2)
{
if(e<rx1)
{
f+=m*(rx1-e);
e=rx1;
}
else if(e>rx2)
{
f+=m*(rx2-e);
e=rx2;
}
if(f<ry1)
{
e+=(ry1-f)/m;
f=ry1;
}
else if(f>ry2)
{
e+=(ry2-f)/m;
f=ry2;
}
}
x1[j]=e;
y1[j]=f;
j++;
}

Output:

Conclusion:
1) Weiler–Atherton clipping algorithm is a polygon-clipping algorithm.
2) It is used in areas like computer graphics and games development where
clipping of polygons is needed.
3) It allows clipping of a subject or candidate polygon by an arbitrarily shaped
clipping polygon/area/region.

You might also like