Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
21 views77 pages

CG Lab Manual

Uploaded by

waghjayesh07
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)
21 views77 pages

CG Lab Manual

Uploaded by

waghjayesh07
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/ 77

DEPARTMENT OF COMPUTER ENGINEERING

ACADEMIC YEAR : 2024–25 (TERM – I)

List of Experiments
Course Name : Computer Graphics Lab (R 19)
Datta Meghe College of Engineering
Course Code :CSC305, CSL302
Airoli, Navi Mumbai

Sr. Name of experiment COs Covered Page Date of Date of Marks &
No. No. Performance Submission Signature
1 To implement Digital CSC305.2
Differential Analyzer line
drawing algorithm.
2 To implement line using CSC305.2
Bresenham’s Line Drawing
Algorithm.
3 To implement Midpoint Circle CSC305.2
Generation Algorithm.
4 To implement Area Filling CSC305.2
Algorithm.
5 To implement Bit Map method CSC305.2
for given Character Generation.
6 To apply the basic 2D CSC305.3
Transformations such as
Translation, Scaling, Rotation
for a given 2D objects.
7 To implement Cohen and CSC305.4
Sutherland Line Clipping
Algorithm.
8 CSC305.5
To implement Bezier Curve.
9 To implement Fractal CSC305.5
Generation (Koch curve).
10 To implement program for CSC305.5
projection of 3D object on
Projection Plane.
To implement Bresenham’s CSC305.2
11
Generation Algorithm.
To implement Mirror Reflection CSC305.2
12
about a line.
11 Assignment I CSC303.1
CSC303.2
CSC303.3
12 Assignment II CSC303.4
CSC303.5
CSC303.6
13 Mini Project All

This is to certify that Mr. / Miss ___________________________________________________ of


__________________ Roll No. __________ has performed the Experiments / Assignments / Tutorials /
Case Study Work mentioned above in the premises of the institution.

________________________
Practical Incharge
DATTA MEGHE COLLEGE OF ENGINEERING, AIROLI, NAVI
MUMBAI

DEPARTMENT OF COMPUTER ENGINEERING

Institute Vision : To create value - based technocrats to fit in the world of work and research

Institute Mission :  To adopt the best engineering practices


 To empower students to work in the world of technology and
research
 To create competent human beings

Department Vision : To provide an intellectually stimulating environment for education,


technological excellence in computer engineering field and professional
training along with human values.

Department Mission :

M1: To promote an educational environment that combines academics with intellectual curiosity.
M2: To develop human resource with sound knowledge of theory and practical in the discipline of
Computer Engineering and the ability to apply the knowledge to the benefit of society at large.
M3: To assimilate creative research and new technologies in order to facilitate students to be a lifelong
learner who will contribute positively to the economic well-being of the nation.

Program Educational Objectives (PEO)

PEO1: To explicate optimal solutions through application of innovative computer science


techniques that aid towards betterment of society.
PEO2: To adapt recent emerging technologies for enhancing their career opportunity
prospects.
PEO3: To effectively communicate and collaborate as a member or leader in a team to manage
multidisciplinary projects.
PEO4: To prepare graduates to involve in research, higher studies or to become entrepreneurs
in long run.

Program Specific Outcomes (PSO)

PSO1: To apply basic and advanced computational and logical skills to provide solutions to
computer engineering problems.
PSO2: Ability to apply standard practices and strategies in design and development of
software and hardware based systems and adapt to evolutionary changes in computing
to meet the challenges of the future.
PSO3: To develop an approach for lifelong learning and utilize multi-disciplinary knowledge
required for satisfying industry or global requirements.
Program Outcomes as defined by NBA (PO)

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,


and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
DATTA MEGHE COLLEGE OF ENGINEERING, AIROLI
DEPARTMENT OF COMPUTER ENGINEERING
COURSE NAME: Computer Graphics Lab
COURSE CODE: CSC305/CSL303
YEAR OF STUDY: S.E., SEMESTER: III

COURSE OUTCOMES

CSC305.1
Understand the basic concepts of Computer Graphics.

CSC305.2 Demonstrate various algorithms for basic graphics primitives.

CSC305.3 Apply 2-D geometric transformations on graphical objects.

CSC305.4 Use various Clipping algorithms on graphical objects.

Explore 3-D geometric transformations, curve representation techniques and projections


CSC305.5
methods.

CSC305.6 Explain visible surface detection techniques and Animation.


DATTA MEGHE COLLEGE OF ENGINEERING
DEPARTMENT OF COMPUTER ENGINEERING
ACADEMIC YEAR 2024-25 (TERM I)

SUBJECT: Computer Graphics Lab(CSL303)

SEM: III DIV: A&B


RUBRICS FOR GRADING EXPERIMENTS

Rubric Rubric Title Criteria Marks*


Number
(out of 10)

R1 Punctuality, On-time 3
Completion
Delayed by not more than a Week 2
Time
/ Timeline Delayed more than a Week 1

R2 Knowledge Clear understanding 3


& Concept
Partially understood 2

Weak understanding 1

R3 Result & Im- Correct implementation with Results 3


plementation
Implementation with some errors 2

Partial implementation 1

R4 Documentation Correct Documentation 1

Not documented properly 0

*means obtained marks will be scaled to 10 for Experiments


DATTA MEGHE COLLEGE OF ENGINEERING
DEPARTMENT OF COMPUTER ENGINEERING
ACADEMIC YEAR 2024-25 (TERM I)

SUBJECT: Computer Graphics (CSC305)

SEM: III DIV: A&B


RUBRICS FOR GRADING ASSIGNMENTS

Rubric Rubric Title Criteria Marks


Number
(out of 5)

R1 Punctuality, On-time 2
Completion Time /
Delayed by not more than a Week 1
Timeline
Delayed more than a Week 0

R2 Knowledge & Clear understanding 2


Concept
Partially understood 1

Weak understanding 0

R3 Documentation Correct Documentation 1

Not documented properly 0

*means obtained marks will be scaled to 5 for Assignments


DATTA MEGHE COLLEGE OF ENGINEERING
DEPARTMENT OF COMPUTER ENGINEERING
ACADEMIC YEAR 2024-25 (TERM I)

SUBJECT: Computer Graphics (CSC305)

SEM: III DIV: A&B


RUBRICS FOR GRADING MINI PROJECT

Rubric Rubric Title Criteria Marks


Number
(out of 5)

R1 Punctuality, On-time 2
Completion Time /
Delayed by not more than a Week 1
Timeline
Delayed more than a Week 0

R2 Knowledge & Clear understanding 2


Concept
Partially understood 1

Weak understanding 0

R3 Documentation Correct Documentation 1

Not documented properly 0

*means obtained marks will be scaled to 5 for Mini Project


EXPERIMENT NO:-01
Date of Performance:

Date of Submission:

Aim :
To implement DDA Algorithm for drawing a line segment between two given end

points A (x1, y1)and B(x2, y2) .


Theory:

DDA algorithm is an incremental scan conversion method. The characteristic of the DDA
algorithm is to take unit steps along one coordinate and compute the corresponding values along
the other coordinate. Its faster method for calculating position than direct use of equation
y= mx + c .
Δy= mΔx
It slope is less than or equal to 1, we shape simple at unit x intervals( x=1) and compute each
successive ‘y’ values as Yk+1=Yk+in ‘k’ subscript takes int values starting from 1 for the
1st point increases by 1 unit final endpoint is reached. Since ‘m’ can be any read number
from 0 to 1, calculated ‘y’ values must be rounded to nearest integers. For lines with a
positive slope greater than 1 we required reverses the rows of ‘x’ and ‘y’ .That is we
sample at unity intervals ( y =1). Calculate each succeeding ‘x’ value as Xk+1= Xk+1/ m
This is based on the assumption that lines are to be processed from left end point to right
end point to reverse processing direction, either we have x=-1, Yk+1=Yk-m OR
y=-1, Xk+1=Xk-1/m It absolute value of slope is less than 1 start end point is at left, we get x=1
calculate ‘y’ value such equation Yk+1=Yk+m.
It start end point is at right we set x=-1 equation ‘y’ passing from equation
Yk+1=Yk-m

Algorithm :

1) Read the line end points (x1, y1)and (x2, y2)


2) Calculate dx = x2 –x1 and dy = y2-y1
3) If dx ≥ dy then Length = dx
Else Length = dy
4) dx = x2-x1/length dy = y2- y1/length
5) x = x1 + 0.5 sign(dx) y = y1 + 0.5 sign(dy)
7) I = 1
While ( I ≤ length )
{Plot integer (x), integer(y)
X = x + dx ; Y = y + dy ; I = ++}
8) Stop
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.
3. 3.It eliminates the multiplication in the equation by making use of raster characteristics
DISADVANTAGES OF DDAALGORITHM
1. Floating point arithmetic in DDA algorithm is still time-consuming.
2. The algorithm is orientation dependent. Hence end point accuracy is poor.

Program:

#include<stdio.h>

#include<graphics.h>

#include<math.h>

void main()

float x,y,x1,y1,x2,y2,dx,dy,length;

int i,gd,gm;

clrscr();

/* Read two end points of line

---------------------------------- */

printf("Enter the value of x1 :\t");

scanf("%f",&x1);

printf("Enter the value of y1 :\t");


scanf("%f",&y1);

printf("Enter the value of x2 :\t");

scanf("%f",&x2);

printf("Enter the value of y2 :\t");

scanf("%f",&y2);

/* Initialise graphics mode

---------------------------------- */

detectgraph(&gd,&gm);

initgraph(&gd,&gm,"\\tc\\BGI");

dx=abs(x2-x1);

dy=abs(y2-y1);

if (dx >= dy)

length = dx;

else

length = dy;

dx = (x2-x1)/length;

dy = (y2-y1)/length;

x = x1 + 0.5; /* Factor 0.5 is added to round the values */

y = y1 + 0.5; /* Factor 0.5 is added to round the values */

putpixel (x, y, 15);


i = 1; /* Initialise loop counter */

while(i <= length)

x = x + dx;

y = y + dy;

putpixel (x, y, 15);

i = i + 1;

delay(100); /* Delay is purposely inserted to see

observe the line drawing process */

getch();

closegraph();

Input & Output:


Conclusion: Thus successfully Implemented simplest implementation for lines, the
DDA algorithm interpolates values in interval by computing for each xi the equations xi
= xi−1 +1, yi = yi−1 + m, where Δx = xend − xstart and Δy = yend − ystart and m = Δ
y/Δx.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-02
Date of Performance:

Date of Submission:

Aim :
To implement Bresenham’s line drawing algorithm for drawing a line segment between
two given endpoints A (x1, y2) and B(x2, y2).

Theory:

Bresenham’s Line Drawing Algorithm uses only integer addition and subtraction and
multiplication by 2 and we know that the computer can perform the operations of integer
addition and subtraction very rapidly. To accomplish this algorithm always increments either x
or y by one unit depending on the slope of line. The increment in the other variable is determined
by examining the distance between the actual line location and the nearest pixel. This distance is
called as decision variable or the error.
Mathematical terms: Error or Decision variable is defined as e = Db-Da or Da-Db
Let us define e = Db-Da. Now if e>0 then it implies that Db>Da
i.e., the pixel above the line is closer to the true line.If Db < Da (i.e.,e < 0) then we can say that
the pixel below the line is closer to the true line.
Thus by checking only the sign of error term it is possible to determine the better pixel to
represent the line path.
The error term is initially set as e = 2Δy – Δx
where Δy = y2-y1 and Δx = x2-x1
Then according to the value of e, following actions are taken while (e>=0)
{ y=y+1 ; e = e-2Δx }
x=x+1
e = e + 2Δy
While e>=0
Error is initialized with e = e - 2Δy.

Algorithm :

Bresenham’s Line Algorithm for (m= Δy/ Δx)/<1


1. Read line end points (x1,y1) and (x2,y2) such that they are not equal
[If they are equal then plot the points and exit].
2. Δx=|x2-x1| and Δy=|y2-y1|.
3. [Initialize starting point] x = x1, y = y1
plot(x,y);
DMCE COMPUTER DEPT CG
4. e = 2*Δy – Δx
[Initialize value of decision variable or error to compensate for non-zero intercepts].
5. I = 1 [Initialize counter]
6. while (e > =0)
{y=y+1
e = e – 2 Δx}
}
x = x+1
e = e + 2*Δy
7. Plot(x,y)
8. i = i+1
9. If (i<=Δx) then go to step 6
10. Stop.
BRESENHAMS LINE DRAWING ALGORITHM ADVANTAGES :
Arithmetic- uses fixed points i.e. Integer Arithmetic.
Operations- uses only subtraction and addition in its operations.
Speed- Bresenhams algorithm is faster than DDA algorithm in line drawing
because it performs only addition and subtraction in its calculation and uses only
integer arithmetic so it runs significantly faster.
Accuracy- more efficient and much accurate than DDA algorithm.
Round Off- does not round off but takes the incremental value in its operation.
Expensive- less expensive than DDA algorithm as it uses only addition and subtraction

Program:

#include<stdio.h>

#include<graphics.h>

#include<math.h>

#include<conio.h>

void main()
{

float x,y,x1,y1,x2,y2,dx,dy,e;

int i,gd,gm;

clrscr();

/* Read two end points of line

---------------------------------- */

printf("Enter the value of x1 :\t");

scanf("%f",&x1);

printf("Enter the value of y1 :\t");

scanf("%f",&y1);

printf("Enter the value of x2 :\t");

scanf("%f",&x2);

printf("Enter the value of y2 :\t");

scanf("%f",&y2);

/* Initialise graphics mode

---------------------------------- */

detectgraph(&gd,&gm);

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

dx=abs(x2-x1);

dy=abs(y2-y1);

/* Initialise starting point

-----------------------------*/

x = x 1;

y = y1;
putpixel (x, y, 15) ;

/* Initialise decision variable

-------------------------------- */

e = 2 * dy-dx;

i = 1; /* Initialise loop counter */

do

while(e >= 0)

y = y + 1;

e = e - 2 * dx;

x = x + 1;

e = e + 2 * dy;

i = i + 1;

putpixel (x, y, 15);

while( i <= dx);

getch();

closegraph();

}
Input & Output:

Conclusion: Thus successfully implemented the Bresenham’s line drawing algorithm,


in which next pixel should be selected in order to form a close approximation to a
straight line between two points.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-03.
Date of Performance:

Date of Submission:

Aim :
To implement midpoint circle generation algorithm ff given center (x, y) and radius r.

Theory:

The mid-point circle drawing algorithm is an algorithm used to determine the points needed for
rasterizing a circle.

We use the mid-point algorithm to calculate all the perimeter points of the circle in the first
octant and then print them along with their mirror points in the other octants. This will work
because a circle is symmetric about its centre.

or any given pixel (x, y), the next pixel to be plotted is either (x, y+1) or (x-1, y+1). This can be
decided by following the steps below.

Find the mid-point p of the two possible pixels i.e (x-0.5, y+1)
If p lies inside or on the circle perimeter, we plot the pixel (x, y+1), otherwise if it’s outside we
plot the pixel (x-1, y+1)
Boundary Condition : Whether the mid-point lies inside or outside the circle can be decided by
using the formula:-

Given a circle centered at (0,0) and radius r and a point p(x,y)


F(p) = x2 + y2 – r2
if F(p)<0, the point is inside the circle
F(p)=0, the point is on the perimeter
F(p)>0, the point is outside the circle

In our program, we denote F(p) with P. The value of P is calculated at the mid-point of the two
contending pixels i.e. (x-0.5, y+1). Each pixel is described with a subscript k.

Pk = (Xk — 0.5)2 + (yk + 1)2 – r2


Now,
xk+1 = xk or xk-1 , yk+1= yk +1
∴ Pk+1 = (xk+1 – 0.5)2 + (yk+1 +1)2 – r2
= (xk+1 – 0.5)2 + [(yk +1) + 1]2 – r2
= (xk+1 – 0.5)2 + (yk +1)2 + 2(yk + 1) + 1 – r2
= (xk+1 – 0.5)2 + [ – (xk – 0.5)2 +(xk – 0.5)2 ] + (yk + 1)2 – r2 + 2(yk + 1) + 1
= Pk + (xk+1 – 0.5)2 – (xk – 0.5)2 + 2(yk + 1) + 1
= Pk + (x2k+1 – x2k) – (xk+1 – xk) + 2(yk + 1) + 1
= Pk + 2(yk +1) + 1, when Pk <=0 i.e the midpoint is inside the circle
(xk+1 = xk)
Pk + 2(yk +1) – 2(xk – 1) + 1, when Pk>0 I.e the mid point is outside the circle(xk+1 = xk-1)

The first point to be plotted is (r, 0) on the x-axis. The initial value of P is calculated as follows:-

P1 = (r – 0.5)2 + (0+1)2 – r2
= 1.25 – r
= 1 -r (When rounded off)
Algorithm :

Step 1: Start.
Step 2: Declare x, y, r, xc , yc , P as variables, where (xc , yc) are coordinates of the center.
Step 3: Put x = 0 and y = r
Step 4: Repeat the steps while x ≤ y;
Step 5: Plot (x, y).
Step 6: if (P < 0):
Set P = P + 2x + 3
else if (P >= 0):
Set P = P + 2(x-y) + 5
y=y-1
Step 7: Do x = x + 1
Step 8: End
Advantages:
The mid-point circle algorithm is an efficient algorithm in drawing a circle.
The implementation of the algorithm is easy from the programmer’s point of view.
Disadvantages:
The time consumption of this algorithm is high.

Program:

// Mid-Point Circle Drawing Algorithm


#include<stdio.h>

// Implementing Mid-Point Circle Drawing Algorithm


void midPointCircleDraw(int x_centre, int y_centre, int r)
{
int x = r, y = 0;

// Printing the initial point on the axes


// after translation
printf("(%d, %d) ", x + x_centre, y + y_centre);

// When radius is zero only a single


// point will be printed
if (r > 0)
{
printf("(%d, %d) ", x + x_centre, -y + y_centre);
printf("(%d, %d) ", y + x_centre, x + y_centre);
printf("(%d, %d)\n", -y + x_centre, x + y_centre);
}

// Initialising the value of P


int P = 1 - r;
while (x > y)
{
y++;

// Mid-point is inside or on the perimeter


if (P <= 0)
P = P + 2*y + 1;

// Mid-point is outside the perimeter


else
{
x--;
P = P + 2*y - 2*x + 1;
}

// All the perimeter points have already been printed


if (x < y)
break;

// Printing the generated point and its reflection


// in the other octants after translation
printf("(%d, %d) ", x + x_centre, y + y_centre);
printf("(%d, %d) ", -x + x_centre, y + y_centre);
printf("(%d, %d) ", x + x_centre, -y + y_centre);
printf("(%d, %d)\n", -x + x_centre, -y + y_centre);

// If the generated point is on the line x = y then


// the perimeter points have already been printed
if (x != y)
{
printf("(%d, %d) ", y + x_centre, x + y_centre);
printf("(%d, %d) ", -y + x_centre, x + y_centre);
printf("(%d, %d) ", y + x_centre, -x + y_centre);
printf("(%d, %d)\n", -y + x_centre, -x + y_centre);
}
}
}

// Driver code
int main()
{
// To draw a circle of radius 3 centered at (0, 0)
midPointCircleDraw(0, 0, 3);
return 0;
}

Input & Output:


Conclusion: Thus successfully Implemented the Midpoint Circle drawing algorithm
which is able to find a path through the pixel grid using pixels which are as close as
possible to solutions of x2+y2=r2

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-04.
Date of Performance:

Date of Submission:

Aim :

To implement area filling algorithm.

Theory:

BOUNDARY FILL ALGORITHM:-

The boundary fill algorithm works as its name. This algorithm picks a point inside an
object and starts to fill until it hits the boundary of the object. The color of the boundary and the
color that we fill should be different for this algorithm to work.
Start at a point inside a region
Paint the interior outward toward the boundary
The boundary is specified in a single color

Fill the 4−connected or 8−connected region

void boundaryFill4 (int x, int y, int fill, int boundary)


{ int current; current = getPixel (x,y);
if (current != boundary && current !=fill)
{ setColor(fill);
setPixel(x,y);
boundaryFill4 (x+1, y, fill, boundary);
boundaryFill4 (x−1, y, fill, boundary);
boundaryFill4(x, y+1, fill, boundary);
bonddaryFill4(x, y−1, fill, boundary); } }

FLOOD FILL ALGORITHM :-

ometimes we come across an object where we want to fill the area and its boundary with
different colors. We can paint such objects with a specified interior color instead
of searching for particular boundary color as in boundary filling algorithm.
Instead of relying on the boundary of the object, it relies on the fill color. In other words,
it replaces the interior color of the object with the fill color. When no more pixels
of the original interior color exist, the algorithm is completed.

Used when an area defined with multiple color boundaries
Start at a point inside a region
Replace a specified interior color (old color) with fill color
Fill the 4−connected or 8−connected region until all interior points being replaced
void floodFill4
(int x, int y, int fill, intoldColor)
{
if (getPixel(x,y) == oldColor)
{ setColor(fill);
setPixel(x,y);
floodFill4 (x+1, y, fill, oldColor);
floodFill4 (x−1, y, fill, oldColor);
floodFill4(x, y+1, fill, oldColor);
floodFill4(x, y−1, fill, oldColor); } }

Algorithm :

Program:

#include<stdio.h>

#include<graphics.h>

#include<conio.h>

void flood(int, int, int, int);

void main()

{int gd,gm;

/* Initialise graphics mode

---------------------------------- */

detectgraph(&gd,&gm);

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

rectangle(50,50,100,100);

flood(55,55,4,15);

getch();

closegraph();

void flood(int seed_x,int seed_y,int foreground_col,int background_col)


{

if(getpixel(seed_x,seed_y)!= background_col &&

getpixel(seed_x,seed_y)!= foreground_col)

putpixel(seed_x,seed_y,foreground_col);

flood(seed_x+1,seed_y,foreground_col,background_col);

flood(seed_x-1,seed_y,foreground_col,background_col);

flood(seed_x,seed_y+1,foreground_col,background_col);

flood(seed_x,seed_y-1,foreground_col,background_col);

flood(seed_x+1,seed_y+1,foreground_col,background_col);

flood(seed_x-1,seed_y-1,foreground_col,background_col);

flood(seed_x+1,seed_y-1,foreground_col,background_col);

flood(seed_x-1,seed_y+1,foreground_col,background_col);

Input & Output:


Conclusion: : Thus we have successfully implemented area filling algorithm.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-05.
Date of Performance:

Date of Submission:

Aim :

To implement Bit Map method for given character generation.

Theory:

A simple method for representing the character shapes in a particular typeface is to use
rectangular grid patterns.
 The figure below shows the pattern for the particular letter.
 When the pattern in the figure copied to the area of the frame buffer, the 1 bits designate
which pixel positions to displayed on the monitor.
 Bitmap fonts the simplest to define and display as character grid only need to be mapped
to a framebuffer position.
 Bitmap fonts require more space because each variation (size and format) must stored in
a font cache.
 It possible to generate different size and other variation from one set but this usually does
not produce the good result.

It is also called dot matrix because in this method characters are represented by an array of
dots in the matrix form. It is a two dimensional array having columns and rows. An 5x7 array
is commonly used to represent characters. However 7x9 and 9x13 arrays are also used. High-
er resolution devices such as inkjet printer or laser printer may use character arrays that are
over 100x100.

Each dot in the matrix is a pixel. The character is placed on the screen by copying pixel val-
ues from the character array into some portion of the screen’s frame buffer. The value of the
pixel controls the intensity of the pixel.
Algorithm :

Program:

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

void main()

int gd=DETECT,gm,i,j;

int a[20][20]=

{{0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0},

{0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0},

{0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1},

{1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0},

{1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0},
{1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,0},

{1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0},

{0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0},

{0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0},

{0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0}};

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

for(i=0;i<19;i++)

for(j=0;j<19;j++)

if(a[i][j]==1)

putpixel(100+j,200+i,WHITE);

getch();

Input & Output:


Conclusion: : Thus we have successfully implemented Bitmap Character Generation
method to generate a Character.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-06.
Date of Performance:

Date of Submission:

Aim :

To apply the basic 2D transformations such as translation, Scaling, Rotation for a given
2D object.

Theory:

TRANSLATION: -
It is a process of changing the position of an object in a straight line path from one
co-ordinate location to another. We can translate a two dimensional points by adding translation
distance tx,ty to original co-ordinate position (x,y) to move point to new position (x,y) to (x',y')
as shown in figure.

The translation distance vector point ( tx,ty ) is called a translation vector or shift vector. It is
possible to express translation equation in a single matrix equation as a column vector to repre-
sent co-ordinate positions and translation vector or shift vector.

It is possible to express translation equation as a single matrix using column vector to represent
co-ordinate position and translation vector.

This allows us to write two dimensional translation equations to matrix form.


P' = P + T
ROTATION:-
A two dimensional rotation is applied to an object by repositioning it along a circular path in
x-y plane.
To generate a rotation we specify rotation angle _ and position of rotation.
x' = rcos(Φ+Θ) y' = rsin (Φ+Θ)

The equation for rotation is


x' = rcos(Φ+Θ) + rsin (Φ+Θ)
y' = - rsin (Φ+Θ) + rcos(Φ+Θ)
The rotation matrix can be given as
R= cosΘ sinΘ
-sinΘ cosΘ

Homogeneous co-ordinate for rotation


R= cosΘ sinΘ 0
-sinΘ cosΘ 0
0 0 1

SCALING:-
A scaling transformation changes size of an object scaling factor Sx scale object in x direction
Sy in y-direction.
x' = x.Sx y' = y.Sy

The equation can be written as

Homogeneous co-ordinate for scaling.S =


Algorithm :

TRANSLATION: -
1. Read vertices of polygon.
2. Read translation vector tx and ty.
3. For i = 0 to vertex * 2
Add tx and ty to each polygon vertex.
4. End for.
5. Draw polygon.
6. Stop.
ROTATION: -
1. Read vertices of polygon.
2. Read angle of rotation.
3. For i = to vertex * 2
Poly[i] = Poly[i]cosΘ -
Poly[i+1]sinΘ Poly[i] =
Poly[i]sinΘ - Poly[i+1]cos.Θ
4. Draw polygon.
5. Stop.
SCALING :

1. Read vertices of polygon.


2. Read scaling factor Sx and Sy.
3. For (i =0 to
vertex*2)
Poly[i] =
Poly[i] * Sx
Poly [i+1] = Poly [i+1] * Sy.
4. Draw polygon.
5. Stop.

Program:

include<graphics.h>

#include<conio.h>

#include<math.h>

#include<stdio.h>

int main()
{

int i, x, y, tx, ty, sx, sy, angle=10, xmax, ymax, xmid, ymid, op;

int gd,gm;

float p1[10]= { 50,50,

100,50,

100,100,

50,100,

50,50,

};

int pi[10];

float b[3][3]={ 1,0,0,

0,1,0,

0,0,1

};

int c[1][1];

float a[1][1];

printf("\nSelect the transformation : ");

printf("\n1 : Traslation");

printf("\n2 : Rotation");

printf("\n3 : Scaling");

printf("\n4 : Rotation about arbitrary point");

printf( "\nEnter the option : ");

scanf("%d",&op);

switch(op)

case 1: printf("\nEnter x traslation : ");

scanf("%d",&tx);
printf("\nEnter y traslation : ");

scanf("%d",&ty);

b[0][0] = 1;

b[0][1] = 0;

b[0][2] = 0;

b[1][0] = 0;

b[1][1] = 1;

b[1][2] = 0;

b[2][0] = tx;

b[2][1] = ty;

b[2][2] = 1;

break;

case 2: printf("\nEnter Rotation angle : ");

scanf("%d",&angle);

b[0][0] =cos(angle*3.142/180);

b[0][1] =sin(angle*3.142/180);

b[0][2] = 0;

b[1][0] =-sin(angle*3.142/180);

b[1][1] = cos(angle*3.142/180);

b[1][2] = 0;

b[2][0] = 0;
b[2][1] = 0;

b[2][2] = 1;

break;

case 3: printf("\nEnter x scaling : ");

scanf("%d",&sx);

printf("\nEnter y scaling : ");

scanf("%d",&sy);

b[0][0] = sx;

b[0][1] = 0;

b[0][2] = 0;

b[1][0] = 0;

b[1][1] = sy;

b[1][2] = 0;

b[2][0] = 0;

b[2][1] = 0;

b[2][2] = 1;

break;

case 4: printf("\nEnter x coordinate of arbitrary point : ");

scanf("%d",&x);

printf("\nEnter y coordinate of arbitrary point : ");

scanf("%d",&y);

printf("\nEnter Rotation angle : ");


scanf("%d",&angle);

tx = x;

ty = y;

b[0][0] =cos(angle*3.142/180);

b[0][1] =sin(angle*3.142/180);

b[0][2] = 0;

b[1][0] =-sin(angle*3.142/180);

b[1][1] = cos(angle*3.142/180);

b[1][2] = 0;

b[2][0] = -tx* cos(angle*3.142/180) + ty*sin(angle*3.142/180)+tx;

b[2][1] = -tx* sin(angle*3.142/180) - ty*cos(angle*3.142/180)+ty;

b[2][2] = 1;

detectgraph(&gd,&gm);

initgraph(&gd,&gm,"\\tc\\bgi"); // Initialize graphics

xmax = getmaxx(); // Get maximum x coordinate

ymax = getmaxy(); // Get maximum y coordinate

xmid = xmax/2; // Get the center x coordinate

ymid = ymax/2; // Get the center y coordinate

setcolor(1);

line(xmid,0,xmid,ymax); // Draw y coordinate


line(0, ymid, xmax, ymid); // Draw x coordinate

setcolor(4);

for (i=0; i<8;i=i+2)

line(p1[i]+xmid,ymid-p1[i+1],xmid+p1[i+2],ymid-p1[i+3]);

for(i=0;i<9;i=i+2)

{ a[0][0]=p1[i];

a[0][1]=p1[i+1];

c[0][0] = a[0][0]*b[0][0]+a[0][1]*b[1][0]+b[2][0];

c[0][1] = a[0][0]*b[0][1]+a[0][1]*b[1][1]+b[2][1];

pi[i]=c[0][0];

pi[i+1]=c[0][1];

setcolor(15);

for (i=0; i<8;i=i+2)

line(xmid+pi[i],ymid-pi[i+1],xmid+pi[i+2],ymid-pi[i+3]);

getch();

closegraph();

return 0;

}
Input & Output:

Conclusion: : Successfully Implemented basic 2D transformations such as


translation,Scaling, Rotation for a given 2D object.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-07.
Date of Performance:

Date of Submission:

Aim :
To implement Cohenen and Sutherland Line Clipping Algorithm for given line Segment and
clipping window.

Theory:

THEORY:-
Sutherland and Cohen Subdivision Line Clipping Algorithm This is one of the oldest and most
popular line clipping algorithm developed by Dan Cohen and Ivan Sutherland. To speed up the
processing, this algorithm performs initial tests that reduce the no of intersections that must be
calculated .The algorithm uses four digit (bit) codes to indicate which of the nine regions
contains the endpoint of line. These four bit codes are called as region code or out codes. These
codes identify the location of point relative to the boundaries of the clipping rectangle as shown
below.

REGION CODE
Each bit position in the region code is used to produce one of the four relative coordinate
positions of the point with respect to clipping window to left, right, top or bottom. The right hand
bit is the first bit and bits are set to
Bit 1 is set to X <Xwmin
Bit 2 is set to X >Xwmin
Bit 3 is set to Y <Ywmin
Bit 4 is set to Y >Ywmin
Region code is used to determine which line is completely inside or outside for intersection of
the line with window boundary.

Point outside window is compared to boundary of window to determine how much line is to
discarded and remaining part of line is checked against other boundary.
For line end point P1(X1,Y1),P2(X2,Y2) intersection point with clipping boundary is
calculated using slope intersection formula for line equation as

1. Y co-ordinate of intersection with vertical boundaries


Y=Y1+m(X-X1)
X is neither Xwmin nor Xwmax depending on boundary of window.
2. X co-ordinate of intersection point inserted with horizontal boundaries
X=X1+ (Y-Y1) /m
Y is neither Ywmin nor Ywmax depending on boundary of window.
Algorithm :

1) Read line end points (X1, Y1) and (X2, Y2).


2) Read clipping window co-ordinate.
3) Read m= Y2-Y1/ X2-X1
4) Assign region code.
5) If code = 0000 accept entire line and go to step 12.
6) If intercept = Left XLY= m (XL-X1) +Y1.
7) If intercept = Right XRY= m (XR-X1) +Y1.
8) If intercept = Bottom Y2X= X1+1 (YB-Y1) / m
9) If intercept = Top Y1X= X1+1 (YT-Y1) / m and go to step 11.
10) Else discard entire line.
11) Discard portion of line which is outside of clip window.
12) Stop.

Program:

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#include<dos.h>

#include<math.h>

#include<graphics.h>

/* Defining structure for end point of line */

typedef struct coordinate

int x,y;

char code[4];

}PT;

void drawwindow();

void drawline (PT p1,PT p2,int cl);


PT setcode(PT p);

int visibility (PT p1,PT p2);

PT resetendpt (PT p1,PT p2);

main()

int gd=DETECT, gm,v;

PT p1,p2,ptemp;

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

cleardevice();

printf("\n\n\t\tENTER END-POINT 1 (x,y): ");

scanf("%d,%d",&p1.x,&p1.y);

printf("\n\n\t\tENTER END-POINT 2 (x,y): ");

scanf("%d,%d",&p2.x,&p2.y);

cleardevice();

drawwindow();

getch();

drawline(p1,p2,15);

getch();

p1=setcode(p1);

p2=setcode(p2);

v=visibility(p1,p2);

switch(v)

case 0: cleardevice(); /* Line completely visible*/

drawwindow();

drawline(p1,p2,15);

break;
case 1: cleardevice(); /* Line completely invisible */

drawwindow();

break;

case 2: cleardevice(); /* line partly visible */

p1=resetendpt (p1,p2);

p2=resetendpt(p2,p1);

drawwindow();

drawline(p1,p2,15);

break;

getch();

closegraph();

return(0);

/* Function to draw window */

void drawwindow()

setcolor(RED);

line(150,100,450,100);

line(450,100,450,350);

line(450,350,150,350);

line(150,350,150,100);

/* Function to draw line between two points

---------------------------------------------*/

void drawline (PT p1,PT p2,int cl)

{
setcolor(cl);

line(p1.x,p1.y,p2.x,p2.y);

/* Function to set code of the co-ordinates

--------------------------------------------*/

PT setcode(PT p)

PT ptemp;

if(p.y<100)

ptemp.code[0]='1'; /* TOP */

else

ptemp.code[0]='0';

if(p.y>350)

ptemp.code[1]='1'; /* BOTTOM */

else

ptemp.code[1]='0';

if (p.x>450)

ptemp.code[2]='1'; /* RIGHT */

else

ptemp.code[2]='0';

if (p.x<150) /* LEFT */

ptemp.code[3]='1';

else

ptemp.code[3]='0';

ptemp.x=p.x;

ptemp.y=p.y;

return(ptemp);
}

/* Function to determine visibility of line

--------------------------------------------*/

int visibility (PT p1,PT p2)

int i,flag=0;

for(i=0;i<4;i++)

if((p1.code[i]!='0')||(p2.code[i]!='0'))

flag=1;

if(flag==0)

return(0);

for(i=0;i<4;i++)

if((p1.code[i]==p2.code[i]) &&(p1.code[i]=='1'))

flag=0;

if(flag==0)

return(1);

return(2);

/* Function to find new end points

--------------------------------------*/

PT resetendpt (PT p1,PT p2)

PT temp;
int x,y,i;

float m,k;

if( p1.code[3]=='1') /* Cutting LEFT Edge */

x=150;

if(p1.code[2]=='1') /* Cutting RIGHT Edge */

x=450;

if((p1.code[3]=='1')||(p1.code[2]=='1'))

m=(float) (p2.y-p1.y)/(p2.x-p1.x);

k=(p1.y+(m*(x-p1.x)));

temp.y=k;

temp.x=x;

for(i=0;i<4;i++)

temp.code[i]=p1.code[i];

if(temp.y<=350&&temp.y>=100)

return(temp);

if(p1.code[0]=='1') /* Cutting TOP Edge */

y=100;

if(p1.code [1]=='1') /* Cutting BOTTOM Edge */

y=350;

if((p1.code[0]=='1')||(p1.code[1]=='1'))

m=(float)(p2.y-p1.y)/(p2.x-p1.x);

k=(float)p1.x+(float)(y-p1.y)/m;

temp.x=k;

temp.y=y;
for(i=0;i<4;i++)

temp.code[i]=p1.code[i];

return(temp);

else

return(p1);

Input & Output:


Conclusion: Successfully implemented Cohen and Sutherland Line Clipping
Algorithm for Clipping given line segment across the given clipping window.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-08.
Date of Performance:

Date of Submission:

Aim :

To implement Bezier curve.

Theory:

A Bezier curve is determined by defining polygon. They have a compiler no of properties that
make them lengthy useful & convenient for curve and surface design. Picture above shows the
Bezier curve and its four control point.

Bezier curve begin at the first control pts and ends at the fourth. This means if we want to
connect two Bezier curve. We have to make first control point of the second curve to match the
last control point of first curve. To observe line connecting1st and second control points.
Similarly at the end of the curve, the curve is tangent to the arc connecting third and fourth
points. We have to place the third and fourth control point at the first curve on the same line
specified by this and second control point g curve.

The equations for Bezier curve are as follows:


X = x4a3 + 3x3a2 (1-a) + 3x2a(1-a)2 + x1(1-a)3
Y =y4a3 + 3y3a2 (1-a) + 3y2a(1-a)2 + y1(1-a)3
Z = z4a3 + 3z3a2 (1-a) + 3z2a(1-a)2 + z1(1-a)

BEZIER CURVES HAVE THE FOLLOWING PROPERTIES −



They generally follow the shape of the control polygon, which consists of the segments joining
the control points.
They always pass through the first and last control points.
They are contained in the convex hull of their defining control points.
The degree of the polynomial defining the curve segment is one less that the number of
defining polygon point. Therefore, for 4 control points, the degree of the polynomial is 3.
A Bezier curve generally follows the shape of the defining polygon.
The direction of the tangent vector at the end points is same as that of the vector determined by
first and last segments.
The convex hull property for a Bezier curve ensures that the polynomial smoothly follows the
control points.
No straight line intersects a Bezier curve more times than it intersects its control polygon.
They are invariant under an affine transformation.
Bezier curves exhibit global control means moving a control point alters the shape of the whole
curve.
A given Bezier curve can be subdivided at a point t=t0 into two Bezier segments which
join together at the point corresponding to the parameter value t=t0.

Algorithm :

ALGORITHM:
1. Start
2. Read no g control points as n.
3. Read the control point as P(x,y)
4. Draw the convex polygon by joining two points.
5. The Bezier formation is calculated using the point as P(1)=ΣP(k) Bk n(4)
Where n varies from 0.001 to 1 be small interval
B(k)=n(u) = (n,k) - uk(1-u)n-k and (n,k) = n! / (k! (n-k)!)
6. Plot the point (x,y)
7. u=u+0.01
8. repeat step 5 & 7 until u<1
9. stop

Program:

#include <stdio.h>

#include <graphics.h>

#include <conio.h>

#include<stdio.h>

#include<process.h>

int gd,gm,maxx,maxy;

float xxx[4][2];

/* Function to draw line from relative position

specified in array xxx-----------------------*/

void line1(float x2,float y2)

{
line(xxx[0][0],xxx[0][1],x2,y2);

xxx[0][0]=x2;

xxx[0][1]=y2;

/* Bezier function

-------------------- */

void bezier(float xb,float yb,float xc,float yc,float xd,float yd,int n)

float xab,yab,xbc,ybc,xcd,ycd;

float xabc,yabc,xbcd,ybcd;

float xabcd,yabcd;

if (n==0)

line1(xb,yb);

line1(xc,yc);

line1(xd,yd);

else

xab = (xxx[0][0]+xb)/2;

yab = (xxx[0][1]+yb)/2;

xbc = (xb+xc)/2;

ybc = (yb+yc)/2;

xcd = (xc+xd)/2;

ycd = (yc+yd)/2;

xabc = (xab+xbc)/2;

yabc = (yab+ybc)/2;
xbcd = (xbc+xcd)/2;

ybcd = (ybc+ycd)/2;

xabcd = (xabc+xbcd)/2;

yabcd = (yabc+ybcd)/2;

n=n-1;

bezier(xab,yab,xabc,yabc,xabcd,yabcd,n);

bezier(xbcd,ybcd,xcd,ycd,xd,yd,n);

/* Function to initialise graphics

----------------------------------- */

void igraph()

detectgraph(&gd,&gm);

if(gd<0)

puts("CANNOT DETECT A GRAPHICS CARD");

exit(1);

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

void main()

int i;

float temp1,temp2;

igraph();
/* Read two end points and two control points of the curve

---------------------------------------------------------- */

for(i=0;i<4;i++)

printf("Enter (x,y) coordinates of point%d : ",i+1);

scanf("%f,%f",&temp1,&temp2);

xxx[i][0] = temp1;

xxx[i][1] = temp2;

bezier(xxx[1][0],xxx[1][1],xxx[2][0],xxx[2][1],xxx[3][0],xxx[3][1],8);

getch();

closegraph();

Input & Output:


Conclusion: : Successfully implemented cubic Bezier curve using 4 given control
points.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-09.
Date of Performance:

Date of Submission:

Aim :

To implement Fractal generation using Koch curve.

Theory:

FRACTAL:-
A fractal is an object or quantity that displays self-similarity, in a somewhat technical sense, on
all scales. Objects defined by recursive algorithms Fractals need not exhibit exactly the same
structure at all scales, but the same "type" of structures must appear on all scales.
Self‐similarity:- See similar sub‐images within image as we zoom in

EXAMPLES OF FRACTALS:-
Clouds ,Grass, Fire, Modeling mountains (terrain), Coastlin Branches of a tree, Surface of a
sponge

KOCH CURVES :-
Koch Curves Discovered in 1904 by Helge von Koch.
Start with straight line of length 1
Recursively Divide line into 3 equal part
Replace middle section with triangular bump, sides of length 1/3
New length = 4/3
STEPS FOR EACH GENERATION:-

KOCH SNOWFLAKES:-
Can form Koch snowflake by joining three Koch curves Perimeter of snowflake grows
exponentially where Pi is perimeter of the ith snowflake iteration
= 8/5!!
S0,S1,S2 are three iterations (generations) of curve.

KOCH SNOWFLAKES:-
Pseudocode,
to draw Kn:
If (n equals 0) draw straight line
Else
{
Draw Kn-1
Turn left 60°
Draw Kn-1
Turn right 120°
Draw Kn-1
Turn left 60°
Draw Kn-1
}

Algorithm :
Program:

#include<stdio.h>

#include<graphics.h>

#include<stdlib.h>

#define SIN 0.86602540 // sin(60 degrees)

void koch(int x1, int y1, int x2, int y2, int m)

int xx, yy, x[5], y[5], lx, ly, offx = 50, offy = 300;

lx = (x2-x1)/3;

ly = (y2-y1)/3;

x[0] = x1; // Store point p0

y[0] = y1;

x[4] = x2; // Store point p4

y[4] = y2;

x[1] = x[0] + lx; // Store point p1

y[1] = y[0] + ly;

x[3] = x[0] + 2*lx; // Store point p3

y[3] = y[0] + 2*ly;

xx = x[3] - x[1]; // Translate point p2 to origin

yy = y[3] - y[1];

x[2] = xx*(0.5) + yy*(SIN); // Perform rotation for point p3

y[2] = - xx*(SIN) + yy*(0.5);

x[2] = x[2] + x[1]; // Perform inverse translation


y[2] = y[2] + y[1];

if(m>0)

koch(x[0], y[0], x[1], y[1], m-1); // Recursive call to Draw part1

koch(x[1], y[1], x[2], y[2], m-1); // Recursive call to Draw part2

koch(x[2], y[2], x[3], y[3], m-1); // Recursive call to Draw part3

koch(x[3], y[3], x[4], y[4], m-1); // Recursive call to Draw part4

else

line(offx + x[0], offy + y[0] , offx + x[1], offy + y[1]);

line(offx + x[1], offy + y[1] , offx + x[2], offy + y[2]);

line(offx + x[2], offy + y[2] , offx + x[3], offy + y[3]);

line(offx + x[3], offy + y[3] , offx + x[4], offy + y[4]);

void main()

int n, gd, gm;

int x1 = 0, x2 = 550, y1= 0, y2 = 0;

/* Initialise graphics mode

---------------------------------- */

printf("\n Enter the level of curve generation : ");

scanf("%d", &n);

detectgraph(&gd,&gm);

initgraph(&gd,&gm,"\\tc\\bgi");
koch(x1, y1, x2, y2, n); // Draw Koch curve

getch();

closegraph();

Input & Output:

Conclusion: : Successfully implemented Fractal generation using Koch curve using


recursion.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-10.
Date of Performance:

Date of Submission:

Aim :

To implement program for projection of 3D object on projection plane.

Theory:

PARALLEL VIEWING PROJECTIONS


Projection rays (projectors) emanate from a Center of Projection (COP) and intersect Projection
Plane (PP). The COP for parallel projectors is at infinity. The length of a line on the projection
plane is the same as the "true Length".

There are two different types of parallel projections:


If the direction of projection is perpendicular to the projection plane then it is an orthographic
projection. If the direction of projection is not perpendicular to the projection plane then it
is an oblique projection.
Look at the parallel projection of a point (x, y, z). (Note the left handed coordinate system). The
projection plane is at z = 0. x, y are the orthographic projection values and xp, yp are
the oblique projection values (at angle a with the projection plane)

Look at orthographic projection: it is simple, just discard the z coordinates. Engineering


drawings frequently use front, side, top orthographic views of an object. Here are three
orthographic views of an object.
Orthographic projections that show more than 1 side of an object are called axonometric
orthographic projections. The most common axonometric projection is an isometric projection
where the projection plane intersects each coordinate axis in the model coordinate system at an
equal distance.

ISOMETRIC PROJECTION
The projection plane intersects the x, y, z axes at equal distances and the projection plane Normal
makes an equal angle with the three axes.
To form an orthographic projection xp = x, yp= y ,zp = 0. To form different types e.g., Isometric,
just manipulate object with 3D transformations.

OBLIQUE PROJECTION
The projectors are not perpendicular to the projection plane but are parallel from the object to the
projection plane The projectors are defined by two angles A and d where:

A = angle of line (x,y,xp,yp) with projection plane,


d = angle of line (x, y, xp, yp) with x axis in projection plane
L = Length of Line (x,y,xp,yp).
Then:
cos d = (xp - x) / L ------>xp = x + Lcos d ,
sin d = (yp - y) / L ------>yp = y + Lsin d ,
tan A = z / L

Now define L1 = L / z ----> L= L1 z ,


so tan A = z / L = 1 / L1 ; xp = x + z(L1cos d) ; yp = y + z(L1sin d)

|1 0 0 0|
P = |0 1 0 0|
|L1cosq L1sinq 1 0|
|0 0 0 1|

PERSPECTIVE VIEWING PROJECTION


The Perspective viewing projection has a Center of Projection ("eye") at a finite distance from
the projection plane (PP).
So the distance of a line from the projection plane determines its size on the projection plane, i.e.
the farther the line is from the projection plane, the smaller its image on the projection plane. In
the two images above, the projections of L1 = L2 but the actual length of L1 <> L2. Perspective
projection is more realistic since distant objects appear smaller.
Computing the Perspective Projection
Now x / (z+d) = xp/d
xp = x[d / (z+d)]
xp = x / (z / d + 1)
Do same for y (look down the x axis) and get
y p = y / (z / d+1)
zp = 0
Note that we can increase the perspective effect by decreasing d (moving closer). We can
represent this in matrix form by using homogeneuos coordinates as follows:

[xhyhzh w] = [x y z 1] |1 0 0 0 |
|0 1 0 0 |
|0 0 0 1/d|
|0 0 0 1 |
where:
xh = x . yh= y, zh = 0 ,w = (z/d) + 1
And Points on the projection plane are [xpypzp 1] = [xh/w yh/w zh/w 1]
This leads to the same xp, yp as before.

Program:

#include <stdio.h>

#include <stdlib.h>

#include<graphics.h>

#include<conio.h>

void draw3d(int s,int x[20],int y[20],int d);

void main()

int gd=DETECT,gm;

int x[20],y[20],i,s,d;
initgraph(&gd,&gm,"");

printf("Enter the No of sides : ");

scanf("%d",&s);

for(i=0;i<s;i++)

printf("(x%d,y%d) :",i,i);

scanf("%d%d",&x[i],&y[i]);

printf("Depth :");

scanf("%d",&d);

draw3d(s,x,y,d);

getch();

setcolor(14);

for(i=0;i<s-1;i++)

line(x[i]+200,y[i],x[i+1]+200,y[i+1]);

line(x[i]+200,y[i],x[0]+200,y[0]);

getch();//top view

for(i=0;i<s-1;i++)

line(x[i],300,x[i+1],300);

line(x[i],300+d*2,x[i+1],300+d*2);

line(x[i],300,x[i],300+d*2);

line(x[i+1],300,x[i+1],300+d*2);

getch();//side view
for(i=0;i<s-1;i++)

line(10,y[i],10,y[i+1]);

line(10+d*2,y[i],10+d*2,y[i+1]);

line(10,y[i],10+d*2,y[i]);

line(10,y[i+1],10+d*2,y[i+1]);

getch();

closegraph();

void draw3d(int s,int x[20],int y[20],int d)

int i,j,k=0;

for(j=0;j<2;j++)

for(i=0;i<s-1;i++)

line(x[i]+k,y[i]-k,x[i+1]+k,y[i+1]-k);

line(x[i]+k,y[i]-k,x[0]+k,y[0]-k);

k=d;

for(i=0;i<s;i++)

line(x[i],y[i],x[i]+d,y[i]-d);

Input & Output:


Conclusion: : Successfully implemented program for projection of 3D given object.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-11.
Date of Performance:

Date of Submission:

Aim :

To implement Bresenham’s circle generation algorithm circle algorithm for drawing a circle of
given center (x, y) and radius r.plane.

Theory:

The Midpoint circle drawing algorithm considers the eight way symmetry of the circle to
generate it. To achieve best approximation to the true circle we have to select these pixels in the
Raster that fall the least distance from the true circle. Let us assume point P as a last Scan
converted pixel. Now, we have two options either to choose pixel A or pixel B.
The distance of pixels A and B from the origin are, DA = √[(Xi+1) 2+(Yi) 2]
DB = √[(Xi+1)2+(Yi-1)2]

δA = DA – r or δB = DB – r.
For more efficient δA and δB are defined as δA = DA^2 - r^2
δB = DB^2 - r^2
From fig(b) we notice that δA is always the positive &δB is always negative.
Thus δi can be defined as following δi = δA + δB
we can say that if δi<0 , i.e. δA<δB then only x is incremented , otherwise x is
incremented is positive direction & y is incremented in negative direction i.e.
For di<0 , Xi+1 = Xi + 1 and
For di >=0 , Xi+1 = Xi + 1 and Yi+1 = Yi – 1

The equation for di at starting point can be simplified as


di = δA + δB = (Xi + 1)^2 +( Yi)^2 - r^2 +(Xi + 1)^2 (Yi – 1)^2 - r^2
= (0 + 1)^2 +( r)^2 - r^2 +(0 + 1)^2 (r – 1)^2 - r^2 = 3-2r

Similarly, the equation for di+1 for both the options are given as
For d<0 , d = d+4x+6 and
For d>=0 , d=d+4(x+y)+10

Algorithm :

1. Read radius and centre of circle


2. Initially current x=0 current y=radius
3. Initialize decision variable
d = 3 – 2r
4. Draw circle.
5. If d<0
Then d = d + 4(current x) + 6
Else
d = d + 4(current x-y) + 10
(current y) = (current y) – 1
end if
6. Calculate (current x) < (current y)
Go to step 4
Else
Go to step 8
7. Draw circle
8. Stop.
Draw cir ()
Putpixel (x + xc , y + yc)
Putpixel (y + xc , x + yc)
Putpixel (-x + xc , y + yc)
Putpixel (x + xc , -y + yc)
Putpixel (x + xc , -y + yc)
Putpixel (x + xc , -x + yc)
Putpixel (-x + xc , -y + yc)
Putpixel (-y + xc , -x + yc)
Return

Program:

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

void EightWaySymmetricPlot(int xc,int yc,int x,int y)


{
putpixel(x+xc,y+yc,RED);
putpixel(x+xc,-y+yc,YELLOW);
putpixel(-x+xc,-y+yc,GREEN);
putpixel(-x+xc,y+yc,YELLOW);
putpixel(y+xc,x+yc,12);
putpixel(y+xc,-x+yc,14);
putpixel(-y+xc,-x+yc,15);
putpixel(-y+xc,x+yc,6);
}

void BresenhamCircle(int xc,int yc,int r)


{
int x=0,y=r,d=3-(2*r);
EightWaySymmetricPlot(xc,yc,x,y);

while(x<=y)
{
if(d<=0)
{
d=d+(4*x)+6;
}
else
{
d=d+(4*x)-(4*y)+10;
y=y-1;
}
x=x+1;
EightWaySymmetricPlot(xc,yc,x,y);
}
}

int main(void)
{
/* request auto detection */
int xc,yc,r,gdriver = DETECT, gmode, errorcode;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "C:\\TURBOC3\\BGI");

/* read result of initialization */


errorcode = graphresult();

if (errorcode != grOk) /* an error occurred */


{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
printf("Enter the values of xc and yc :");
scanf("%d%d",&xc,&yc);
printf("Enter the value of radius :");
scanf("%d",&r);
BresenhamCircle(xc,yc,r);

getch();
closegraph();
return 0;
}
Input & Output:
Conclusion Thus successfully Implemented the Bresenham’s Circle drawing algorithm
which is able to find a path through the pixel grid using pixels which are as close as
possible to solutions of x2+y2=r2.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)
EXPERIMENT NO:-12.
Date of Performance:

Date of Submission:

Aim :

To implement Mirror Reflection about a line.

Theory:

Reflection:
It is a transformation which produces a mirror image of an object. The mirror image can be either
about x-axis or y-axis. The object is rotated by180°.
Types of Reflection:
Reflection about the x-axis
Reflection about the y-axis
Reflection about an axis perpendicular to xy plane and passing through the origin
Reflection about line y=x
1. Reflection about x-axis: The object can be reflected about x-axis with the help of the
following matrix

In this transformation value of x will remain same whereas the value of y will become negative.
Following figures shows the reflection of the object axis. The object will lie another side of the
x-axis.

2. Reflection about y-axis: The object can be reflected about y-axis with the help of following
transformation matrix
Here the values of x will be reversed, whereas the value of y will remain the same. The object
will lie another side of the y-axis.
The following figure shows the reflection about the y-axis

3. Reflection about an axis perpendicular to xy plane and passing through origin:


In the matrix of this transformation is given below

In this value of x and y both will be reversed. This is also called as half revolution about the
origin.
4. Reflection about line y=x: The object may be reflected about line y = x with the help of
following transformation matrix
First of all, the object is rotated at 45°. The direction of rotation is clockwise. After it reflection
is done concerning x-axis. The last step is the rotation of y=x back to its original position that is
counterclockwise at 45°.

Program:

include <iostream.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
#include <stdlib.h>
#define pi 3.14
class arc
{
float x[10],y[10],theta,ref[10][10],ang;
float p[10][10],p1[10][10],x1[10],y1[10],xm,ym;
int i,k,j,n;
public:
void get();
void cal ();
void map ();
void graph ();
void plot ();
void plot1();
};
void arc::get ()
{
cout<<"\n ENTER ANGLE OF LINE INCLINATION AND Y INTERCEPT";
cin>> ang >> b;
cout <<"\n ENTER NO OF VERTICES";
cin >> n;
cout <<"\n ENTER";
for (i=0; i<n; i++)
{
cout<<"\n x["<<i<<"] and y["<<i<<"]";
}
theta =(ang * pi)/ 180;
ref [0] [0] = cos (2 * theta);
ref [0] [1] = sin (2 * theta);
ref [0] [2] = -b *sin (2 * theta);
ref [1] [0] = sin (2 * theta);
ref [1] [1] = -cos (2 * theta);
ref [1] [2] = b * (cos (2 * theta)+1);
ref [2] [0]=0;
ref [2] [1]=0;
ref [2] [2] = 1;
}
void arc :: cal ()
{
for (i=0; i < n; i++)
{
p[0] [i] = x [i];
p [1] [i] = y [i];
p [2] [i] = 1;
}
for (i=0; i<3;i++)
{
for (j=0; j<n; j++)
{
p1 [i] [j]=0;
for (k=0;k<3; k++)
}
p1 [i] [j] + = ref [i] [k] * p [k] [j];
}
for (i=0; i<n; i++)
{
x1 [i]=p1[0] [i];
y1 [i] = p1 [1] [i];
}
}
void arc :: map ()
{
int gd = DETECT,gm;
initgraph (&gd, &gm, " ");
int errorcode = graphresult ();
/* an error occurred */
if (errorcode ! = grOK)
{
printf ("Graphics error: %s \n", grapherrormsg (errorcode));
printf ("Press any key to halt:");
getch ();
exit (1); /* terminate with an error code */
}
}
void arc :: graph ()
{
xm=getmaxx ()/2;
ym=getmaxy ()/2;
line (xm, 0, xmm 2*ym);
}
void arc :: plot 1 ()
{
for (i=0; i <n-1; i++)
{
circle (x1[i]+xm, (-y1[i]+ym), 2);
line (x1[i]+xm, (-y1[i]+ym), x1[i+1]+xm, (-y1[i+1]+ym));
}
line (x1[n-1)+xm, (-y1[n-1]+ym), x1[0]+xm, (-y1[0]+ym));
getch();
}
void arc :: plot ()
{
for (i=0; i <n-1; i++)
{
circle (x1[i]+xm, (-y1[i]+ym, 2);
line (x1[i]+xm, (-y1[i]+ym), x[i+1]+xm, (-y1[i+1]+ym));
}
line (x[n-1]+xm, (-y1[n-1]+ym), x[0]+xm, (-y[0]+ym));
getch();
}
void main ()
{
class arc a;
clrscr();
a.map();
a.graph();
a.get();
a.cal();
a.plot();
a.plot1();
getch();
}
Input & Output:
Conclusion Thus successfully implemented the Mirror Reflection about a line.

Sign and Remark:

R1 R2 R3 R4 Total Marks Signature


(3) (3) (3) (1) (10)

You might also like