0% found this document useful (0 votes)
33 views46 pages

COMPUTER GRAPHICS LABORATORY AY 2022-2023 8 Practical

1. For scaling, specify scaling factors Sx and Sy and calculate the new coordinates as x' = x * Sx and y' = y * Sy. 2. For translation, specify translation distances Tx and Ty and calculate new coordinates as x' = x + Tx and y' = y + Ty. 3. For rotation, specify the angle of rotation θ and rotation point (px, py). Calculate new coordinates using x' = (x - px)cosθ - (y - py)sinθ + px and y' = (x - px)sinθ + (y - py)cosθ +

Uploaded by

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

COMPUTER GRAPHICS LABORATORY AY 2022-2023 8 Practical

1. For scaling, specify scaling factors Sx and Sy and calculate the new coordinates as x' = x * Sx and y' = y * Sy. 2. For translation, specify translation distances Tx and Ty and calculate new coordinates as x' = x + Tx and y' = y + Ty. 3. For rotation, specify the angle of rotation θ and rotation point (px, py). Calculate new coordinates using x' = (x - px)cosθ - (y - py)sinθ + px and y' = (x - px)sinθ + (y - py)cosθ +

Uploaded by

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

Rajarshi Shahu College of Engineering, Buldana

Department of Computer Science & Engineering

Laboratory Manual for

COMPUTER GRAPHICS-LAB

Semester – VII

Department of Computer Science & Engineering,

RAJARSHI SHAHU
COLLEGE OF ENGINEERING

BULDANA – 443002 (M.S.),

INDIA.

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

RAJARSHI SHAHU
COLLEGE OF ENGINEERING, BULDANA

Department of Computer Science & Engineering

CERTIFICATE

This is to certify that Mr. / Ms.


Roll No. _ of Seventh semester has satisfactory completed the course
experiments in the practical prescribed by Sant Gadge Baba Amravati University,
Amravati in the COMPUTER GRAPHICS-LAB in the year 2022 to 2023 as per the
prescribed curriculum.

Sign of Faculty Head of the Department

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

INDEX

LIST OF EXPERIMENTS AND RECORD OF PROGRESSIVE ASSESSMENT

Exp Page Recor Viva Tota Rem


Tech.
erim No. d 3Ma l arks
Name Of The Experiment DOP DOS Perfor
ent Writin rks Mar
mance
no. g ks
Write a program to draw line using
1 DDA algorithm.

Write a program to draw line using


2 Bresenham‘s algorithm

Write a program for 2-D


3 transformations, a) Scaling b)
Translation c) Rotation

Write a program of man walking in


4 rain

Write program to fill polygon using


5 scan line algorithm

Write a program to clip line using


6 following algorithm : Cohen-
Sutherland algorithm
Write a graphics program analog clock
7
Write a program to draw following
8 type of curve-Koch curve, Bezier
curves

Write a program to fill color


in
9 rectangle

Write a program to
generate
10 snowflake using concept of fractals.

11 Write a program to draw a house

Sign of Faculty

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

EXPERIMENT NO.1

TITLE: Write a program to draw line using DDA algorithm.

PRIOR CONCEPT:

To Learn DDA Algorithm.

ALGORITHM:

Step1: Start Algorithm

Step2: Declare x1,y1,x2,y2,dx,dy,x,y as integer

variables. Step3: Enter value of x1,y1,x2,y2.

Step4: Calculate dx = x2-x1

Step5: Calculate dy = y2-y1

Step6: If ABS (dx) > ABS

(dy)
Then step = abs
(dx) Else

Step7: xinc=dx/step
yinc=dy/step
assign x =
x1 assign y
= y1

Step8: Set pixel (x, y)

Step9: x = x + xinc
y = y + yinc
Set pixels (Round (x), Round

(y)) Step10: Repeat step 9 until x = x2

Step11: End Algorithm

PROGRAM:
#include<graphics.h>

#include<conio.h>

#include<stdio.h>

void main()

intgd = DETECT ,gm,

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering
i; float x, y,dx,dy,steps;

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

int x0, x1, y0, y1;

initgraph(&gd, &gm, "C:\\TC\\

BGI"); setcolor(WHITE);

printf("Enter coordinates for 1st point of

line:"); scanf("%d%d",&x0,&y0);

printf("Enter coordinates for 2nd point of

line:"); scanf("%d%d",&x1,&y1);

dx = (float)(x1 - x0);

dy = (float)(y1 -

y0); if(dx>=dy)

steps = dx;

else

steps = dy;

dx = dx/steps;

dy = dy/steps;

x = x0;

y = y0;

i = 1;

while(i<= steps)

putpixel(x, y, RED);

x += dx;

y +=

dy;

i=i+1;

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

getch();

closegraph();

OUTPUT:

CONCLUSION:

In this way we have studied a program to draw line using DDA algorithm.

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

EXPERIMENT NO:-2

TITLE: Write a program to draw line using Bresenham‘s algorithm.

PRIOR CONCEPT:

To Learn Bresenham‘s algorithm.

ALGORITHM:

Step1: Start Algorithm

Step2: Declare variable x1,x2,y1,y2,d,i1,i2,dx,dy

Step3: Enter value of x1,y1,x2,y2


Where x1,y1are coordinates of starting point
And x2,y2 are coordinates of Ending point

Step4: Calculate dx = x2-x1


Calculate dy = y2-y1
Calculate i1=2*dy
Calculate i2=2*(dy-dx)
Calculate d=i1-dx

Step5: Consider (x, y) as starting point and xendas maximum possible value of x.
If dx < 0
Then x = x2
y = y2
xend=x1
If dx > 0
Then x = x1
y = y1
xend=x2

Step6: Generate point at (x,y)coordinates.

Step7: Check if whole line is generated.


If x > = xend
Stop.

Step8: Calculate co-ordinates of the next pixel


If d < 0
Then d = d + i1
If d ≥ 0
Then d = d + i2
Increment y = y + 1

Step9: Increment x = x + 1

Step10: Draw a point of latest (x, y) coordinates

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

Step11: Go to step 7

Step12: End of Algorithm

PROGRAM:
#include<stdio.h>

#include<conio.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; }}

void main()

int gdriver=DETECT, gmode, error, x0, y0, x1,

y1; clrscr();

initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

printf("Enter co-ordinates of first point: ");

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana
Department of Computer Science & Engineering

scanf("%d%d", &x0, &y0);

printf("Enter co-ordinates of second point:

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

drawline(x0, y0, x1,

y1); getch();}

OUTPUT:

CONCLUSION:

In this way we have studied draw line using Bresenham‘s algorithm.

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

EXPERIMENT NO:-3

TITLE: Write a program for 2-D transformations, a) Scaling b) Translation c) Rotation

PRIOR CONCEPT:

To Learn 2-D transformations, a) Scaling b) Translation c) Rotation

THEORY:

a) Scaling of traingle

Scaling : It is used to change the size of objects. The change is done using scaling factors. There are
two scaling factors, i.e. Sx in x direction Sy in y-direction. If the original position is x and y. Scaling
factors are Sx and Sy .

b) Translation : It is the straight line movement of an object from one position to another is called
Translation. Here the object is positioned from one coordinate location to another.

Translation of point: To translate a point from coordinate position (x, y) to another (x1 y1), we add
algebraically the translation distances Tx and Ty to original coordinate.

x1=x+Tx
y1=y+Ty

c) Rotation : It is a process of changing the angle of the object. Rotation can be clockwise or
anticlockwise. For rotation, we have to specify the angle of rotation and rotation point. Rotation point
is also called a pivot point. It is print about which object is rotated.

Types of Rotation

Anticlockwise - The positive value of the rotation angle rotates an object in a anti-clockwise
direction.Counterclockwise - The negative value of the pivot point (rotation angle) rotates an object
in a clockwise direction.

PROGRAM:
a) Scaling of traingle

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

void fC(int s[][2], int p[][1])

int temp[2][1] = { 0 };

for (int i = 0; i < 2; i+

+)

for (int j = 0; j < 1; j++)

for (int k = 0; k < 2; k++)

temp[i][j] += (s[i][k] * p[k]

[j]);

p[0][0] = temp[0][0];

p[1][0] = temp[1][0];

void scale(int x[], int y[], int sx, int sy)

// Triangle before

Scaling line(x[0], y[0],

x[1], y[1]);

line(x[1], y[1], x[2], y[2]);

line(x[2], y[2], x[0], y[0]);

// Initializing the Scaling

Matrix. int s[2][2] = { sx, 0, 0, sy

};

int p[2][1];

for (int i = 0; i < 3; i++)

p[0][0] = x[i];

p[1][0] = y[i];

fC(s, p);

x[i] = p[0][0];

y[i] = p[1][0];
COMPUTER GRAPHICS Lab Page
Rajarshi Shahu College of Engineering,
Buldana

line(x[0], y[0], x[1], y[1]);

line(x[1], y[1], x[2], y[2]);

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

line(x[2], y[2], x[0], y[0]);

void main()

int x[] = { 100, 200, 300 };

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

int sx = 2, sy =

2; int gd, gm;

detectgraph(&gd, &gm);

initgraph(&gd, &gm,"

");

scale(x, y, sx,sy);

getch();

a)OUTPUT:

b) Translation:-

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

void main()

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana
int gd=DETECT , gm ;

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

int x3,y3,x1,y1,x2,y2,tx,ty;

clrscr();

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

printf("\n enter first coordinate : ");

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

printf("\n enter second coordinate:

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

printf("\n enter third coordinate:

"); scanf("%d%d",&x3,&y3);

line(x1,y1,x2,y2);

line(x2,y2,x3,y3);

line(x3,y3,x1,y1);

printf("\n enter translation vectors :

"); scanf("%d%d",&tx,&ty);

setcolor(BLUE);

line(x1+tx,y1+ty,x2+tx,y2+ty);

line(x2+tx,y2+ty,x3+tx,y3+ty);

line(x3+tx,y3+ty,x1+tx,y1+ty);

getch();

closegraph();}

b)OUTPUT:

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

c) Rotation:-

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

#include<math.h>

void main()

int gd=0,gm,x1,y1,x2,y2,x3,y3;

double s,c, angle;

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

setcolor(RED);

printf("Enter coordinates of triangle: "); scanf("%d%d%d

%d%d%d",&x1,&y1,&x2,&y2, &x3, &y3);

setbkcolor(WHITE);

cleardevice();

line(x1,y1,x2,y2);

line(x2,y2, x3,y3);

line(x3, y3, x1,

y1); getch();

setbkcolor(BLACK); //setting background

color printf("Enter rotation angle: ");

scanf("%lf", &angle);

setbkcolor(WHITE); //setting background color

//M_PI : Pi, the ratio of a circle’s circumference to its

diameter. c = cos(angle *M_PI/180);

s = sin(angle *M_PI/180);

x1 = floor(x1 * c + y1 * s);

y1 = floor(-x1 * s + y1 *

c); x2 = floor(x2 * c + y2 *

s);
COMPUTER GRAPHICS Lab Page
Rajarshi Shahu College of Engineering,
Buldana

y2 = floor(-x2 * s + y2 *

c); x3 = floor(x3 * c + y3 *

s); y3 = floor(-x3 * s + y3

* c); cleardevice();

line(x1, y1 ,x2, y2);

line(x2,y2, x3,y3);

line(x3, y3, x1,

y1); getch();

closegraph();

C)OUTPUT:

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

CONCLUSION:

In this way we have studied a program for 2-D transformations, a) Scaling b) Translation c) Rotation.

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

EXPERIMENT NO:-4

TITLE: Write a program a man walking in the rain.

PRIOR CONCEPT:

To Learn graphics approch.

THEORY:

In this program, we will create scenery with a hut, sun, and rainfall. In this scenery, a man holds an
umbrella and walks through the ground. When a key is pressed, the rain stops, and a rainbow
appears.
 Ground Level: To create a ground line, we will first use GroundY ScreenHeight to define the
ground level.
 Hut: The hut will be built for the scenery. For the base and roof, rectangles and lines will be
used. The hut will be colorful.
 Man and Umbrella: Build a man holding an umbrella. A circle forms the head of the man, and
lines make up his body. Lines representing the legs have variable coordinates so it appears as if
the man is walking on the ground. Using the pieslice function we will create the body of an
umbrella and lines for the stick.
 Rain: Create rain using the rand() function to generate random pixels and create small lines to
create a rain effect
 Circle: To create a sun in the top left corner we will use a circle.
 Rainbow: Create a rainbow in the top left corner using the arc function. The delay function
gives it an animation.
 Rainfall continues until any key is pressed.
 The rainbow appears when a key is pressed.
PROGRAM:
// C program to implement
// the above approach
#include <conio.h>
#include <graphics.h>
#include <stdio.h>
#define ScreenWidth getmaxx()
#define ScreenHeight getmaxy()
#define GroundY ScreenHeight * 0.75
int ldisp = 0;

// Creating a hut
void hut()
{
setcolor(WHITE);
rectangle(150, 180, 250, 300);
rectangle(250, 180, 420, 300);
rectangle(180, 250, 220, 300);

line(200, 100, 150, 180);


line(200, 100, 250, 180);
line(200, 100, 370, 100);
line(370, 100, 420, 180);

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

setfillstyle(SOLID_FILL, BROWN);
floodfill(152, 182, WHITE);
floodfill(252, 182, WHITE);
setfillstyle(SLASH_FILL, BLUE);
floodfill(182, 252, WHITE);
setfillstyle(HATCH_FILL, GREEN);
floodfill(200, 105, WHITE);
floodfill(210, 105, WHITE);
}

// Drawing a Man with


// an umbrella
void DrawManAndUmbrella(int x,
int ldisp)
{
circle(x, GroundY - 90, 10);
line(x, GroundY - 80, x,
GroundY - 30);
line(x, GroundY - 70,
x + 10, GroundY - 60);
line(x, GroundY - 65, x + 10,
GroundY - 55);
line(x + 10, GroundY - 60,
x + 20, GroundY - 70);
line(x + 10, GroundY - 55,
x + 20, GroundY - 70);

line(x, GroundY - 30,


x + ldisp, GroundY);
line(x, GroundY - 30,
x - ldisp, GroundY);

pieslice(x + 20, GroundY - 120,


0, 180, 40);
line(x + 20, GroundY - 120,
x + 20, GroundY - 70);
}

// Creating the Rainfall


void Rain(int x)
{
int i, rx, ry;
for (i = 0; i < 400; i++)
{
rx = rand() % ScreenWidth;
ry = rand() % ScreenHeight;
if (ry < GroundY - 4)
{
if (ry < GroundY - 120 ||
(ry > GroundY - 120 &&
(rx < x - 20 ||
rx > x + 60)))
line(rx, ry,
rx + 0.5, ry + 4);
}
}
}

// Creating the rainbow


void rainbow()

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

{
int x, y, i;

circle(ScreenWidth - 100,
50, 30);
setfillstyle(SOLID_FILL,
YELLOW);
floodfill(ScreenWidth - 100,
50, WHITE);

ldisp = (ldisp + 2) % 20;


DrawManAndUmbrella(x, ldisp);
hut();
x = getmaxx() / 5;
y = getmaxy() / 5;

for (i = 30; i < 100; i++)


{
// for animation
delay(50);

setcolor(i / 10);

arc(x, y, 0, 180, i - 10);


}
getch();
}

// Driver code
void main()
{
int gd = DETECT, gm, x = 0;

initgraph(&gd, &gm, "C:\\


TurboC3\\BGI");

// executes till any key


// is pressed
while (!kbhit())
{
hut();
circle(ScreenWidth - 100,
50, 30);
setfillstyle(SOLID_FILL,
YELLOW);
floodfill(ScreenWidth - 100,
50, WHITE);
line(0, GroundY, ScreenWidth,
GroundY);
Rain(x);

ldisp = (ldisp + 2) % 20;


DrawManAndUmbrella(x, ldisp);
delay(20);
cleardevice();
x = (x + 2) % ScreenWidth;
}
// if the key is pressed the
// rain stops, rainbow appears
ldisp = (ldisp + 2) % 20;

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

DrawManAndUmbrella(x, ldisp);
rainbow();
getch();
}

OUTPUT:

CONCLUSION:

In this way we have studied a program a man walking in the rain.

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

EXPERIMENT NO:-5

TITLE: Write program to fill polygon using scan line algorithm

PRIOR CONCEPT:

To Learn line Algorithm.

THEORY:

1. We will process the polygon edge after edge, and store in the edge Table.
2.Storing is done by storing the edge in the same scanline edge tuple as
the lowermost point's y-coordinate value of the edge.
3.After addition of any edge in an edge tuple, the tuple is
sorted using insertion sort, according to its xofymin value.
4.After the whole polygon is added to the edge table,
the figure is now filled.
5.Filling is started from the first scanline at the bottom,
and continued till the top.
6.Now the active edge table is taken and the following things
are repeated for each scanline:
i. Copy all edge buckets of the designated scanline
to the active edge tuple
ii. Perform an insertion sort according
to the xofymin values
iii. Remove all edge buckets whose ymax is equal
or greater than the scanline
iv.Fillup pairs of edges in active tuple, if any vertex is got,
follow these instructions:
o If both lines intersecting at the vertex are on
the same side of the scanline, consider it as two points.
o If lines intersecting at the vertex are at
opposite sides of the scanline, consider it as only one point.
v. Update the xofymin by adding slopeinverse for each bucket.

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

PROGRAM:
// CPP program to illustrate
// Scanline Polygon fill Algorithm

#include <stdio.h>
#include <math.h>
#include <GL/glut.h>
#define maxHt 800
#define maxWd 600
#define maxVer 10000

FILE *fp;

// Start from lower left corner


typedef struct edgebucket
{
int ymax; //max y-coordinate of edge
float xofymin; //x-coordinate of lowest edge point updated only in aet
float slopeinverse;
}EdgeBucket;

typedef struct edgetabletup


{
// the array will give the scanline number
// The edge table (ET) with edges entries sorted
// in increasing y and x of the lower end

int countEdgeBucket; //no. of edgebuckets


EdgeBucket buckets[maxVer];
}EdgeTableTuple;

EdgeTableTuple EdgeTable[maxHt], ActiveEdgeTuple;

// Scanline Function
void initEdgeTable()
{
int i;
for (i=0; i<maxHt; i++)
{
EdgeTable[i].countEdgeBucket = 0;
}

ActiveEdgeTuple.countEdgeBucket = 0;
}

void printTuple(EdgeTableTuple *tup)


{
int j;

if (tup->countEdgeBucket)
printf("\nCount %d-----\n",tup->countEdgeBucket);

for (j=0; j<tup->countEdgeBucket; j++)


{

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

printf(" %d+%.2f+%.2f",
tup->buckets[j].ymax, tup->buckets[j].xofymin,tup->buckets[j].slopeinverse);
}
}

void printTable()
{
int i,j;

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


{
if (EdgeTable[i].countEdgeBucket)
printf("\nScanline %d", i);

printTuple(&EdgeTable[i]);
}
}

/* Function to sort an array using insertion sort*/


void insertionSort(EdgeTableTuple *ett)
{
int i,j;
EdgeBucket temp;

for (i = 1; i < ett->countEdgeBucket; i++)


{
temp.ymax = ett->buckets[i].ymax;
temp.xofymin = ett->buckets[i].xofymin;
temp.slopeinverse = ett->buckets[i].slopeinverse;
j = i - 1;

while ((temp.xofymin < ett->buckets[j].xofymin) && (j >= 0))


{
ett->buckets[j + 1].ymax = ett->buckets[j].ymax;
ett->buckets[j + 1].xofymin = ett->buckets[j].xofymin;
ett->buckets[j + 1].slopeinverse = ett->buckets[j].slopeinverse;
j = j - 1;
}
ett->buckets[j + 1].ymax = temp.ymax;
ett->buckets[j + 1].xofymin = temp.xofymin;
ett->buckets[j + 1].slopeinverse = temp.slopeinverse;
}
}

void storeEdgeInTuple (EdgeTableTuple *receiver,int ym,int xm,float slopInv)


{
// both used for edgetable and active edge table..
// The edge tuple sorted in increasing ymax and x of the lower end.
(receiver->buckets[(receiver)->countEdgeBucket]).ymax = ym;
(receiver->buckets[(receiver)->countEdgeBucket]).xofymin = (float)xm;
(receiver->buckets[(receiver)->countEdgeBucket]).slopeinverse = slopInv;

// sort the buckets


insertionSort(receiver);

(receiver->countEdgeBucket)++;

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

void storeEdgeInTable (int x1,int y1, int x2, int y2)


{
float m,minv;
int ymaxTS,xwithyminTS, scanline; //ts stands for to store

if (x2==x1)
{
minv=0.000000;
}
else
{
m = ((float)(y2-y1))/((float)(x2-x1));

// horizontal lines are not stored in edge table


if (y2==y1)
return;

minv = (float)1.0/m;
printf("\nSlope string for %d %d & %d %d: %f",x1,y1,x2,y2,minv);
}

if (y1>y2)
{
scanline=y2;
ymaxTS=y1;
xwithyminTS=x2;
}
else
{
scanline=y1;
ymaxTS=y2;
xwithyminTS=x1;
}
// the assignment part is done..now storage..
storeEdgeInTuple(&EdgeTable[scanline],ymaxTS,xwithyminTS,minv);

void removeEdgeByYmax(EdgeTableTuple *Tup,int yy)


{
int i,j;
for (i=0; i< Tup->countEdgeBucket; i++)
{
if (Tup->buckets[i].ymax == yy)
{
printf("\nRemoved at %d",yy);

for ( j = i ; j < Tup->countEdgeBucket -1 ; j++ )


{
Tup->buckets[j].ymax =Tup->buckets[j+1].ymax;
Tup->buckets[j].xofymin =Tup->buckets[j+1].xofymin;
Tup->buckets[j].slopeinverse = Tup->buckets[j+1].slopeinverse;
}

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

Tup->countEdgeBucket--;
i--;
}
}
}

void updatexbyslopeinv(EdgeTableTuple *Tup)


{
int i;

for (i=0; i<Tup->countEdgeBucket; i++)


{
(Tup->buckets[i]).xofymin =(Tup->buckets[i]).xofymin + (Tup->buckets[i]).slopeinverse;
}
}

void ScanlineFill()
{
/* Follow the following rules:
1. Horizontal edges: Do not include in edge table
2. Horizontal edges: Drawn either on the bottom or on the top.
3. Vertices: If local max or min, then count twice, else count
once.
4. Either vertices at local minima or at local maxima are drawn.*/

int i, j, x1, ymax1, x2, ymax2, FillFlag = 0, coordCount;

// we will start from scanline 0;


// Repeat until last scanline:
for (i=0; i<maxHt; i++)//4. Increment y by 1 (next scan line)
{

// 1. Move from ET bucket y to the


// AET those edges whose ymin = y (entering edges)
for (j=0; j<EdgeTable[i].countEdgeBucket; j++)
{
storeEdgeInTuple(&ActiveEdgeTuple,EdgeTable[i].buckets[j].
ymax,EdgeTable[i].buckets[j].xofymin,
EdgeTable[i].buckets[j].slopeinverse);
}
printTuple(&ActiveEdgeTuple);

// 2. Remove from AET those edges for


// which y=ymax (not involved in next scan line)
removeEdgeByYmax(&ActiveEdgeTuple, i);

//sort AET (remember: ET is presorted)


insertionSort(&ActiveEdgeTuple);

printTuple(&ActiveEdgeTuple);

//3. Fill lines on scan line y by using pairs of x-coords from AET
j = 0;
FillFlag = 0;

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

coordCount = 0;
x1 = 0;
x2 = 0;
ymax1 = 0;
ymax2 = 0;
while (j<ActiveEdgeTuple.countEdgeBucket)
{
if (coordCount%2==0)
{
x1 = (int)(ActiveEdgeTuple.buckets[j].xofymin);
ymax1 = ActiveEdgeTuple.buckets[j].ymax;
if (x1==x2)
{
/* three cases can arrive-
1. lines are towards top of the intersection
2. lines are towards bottom
3. one line is towards top and other is towards bottom
*/
if (((x1==ymax1)&&(x2!=ymax2))||((x1!=ymax1)&&(x2==ymax2)))
{
x2 = x1;
ymax2 = ymax1;
}

else
{
coordCount++;
}
}

else
{
coordCount++;
}
}
else
{
x2 = (int)ActiveEdgeTuple.buckets[j].xofymin;
ymax2 = ActiveEdgeTuple.buckets[j].ymax;

FillFlag = 0;

// checking for intersection...


if (x1==x2)
{
/*three cases can arrive-
1. lines are towards top of the intersection
2. lines are towards bottom
3. one line is towards top and other is towards bottom
*/
if (((x1==ymax1)&&(x2!=ymax2))||((x1!=ymax1)&&(x2==ymax2)))
{
x1 = x2;
ymax1 = ymax2;
}
else
{
coordCount++;
FillFlag = 1;

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

}
}
else
{
coordCount++;
FillFlag = 1;
}

if(FillFlag)
{
//drawing actual lines...
glColor3f(0.0f,0.7f,0.0f);

glBegin(GL_LINES);
glVertex2i(x1,i);
glVertex2i(x2,i);
glEnd();
glFlush();

// printf("\nLine drawn from %d,%d to %d,%d",x1,i,x2,i);


}

j++;
}

// 5. For each nonvertical edge remaining in AET, update x for new y


updatexbyslopeinv(&ActiveEdgeTuple);
}

printf("\nScanline filling complete");

void myInit(void)
{

glClearColor(1.0,1.0,1.0,0.0);
glMatrixMode(GL_PROJECTION);

glLoadIdentity();
gluOrtho2D(0,maxHt,0,maxWd);
glClear(GL_COLOR_BUFFER_BIT);
}

void drawPolyDino()
{

glColor3f(1.0f,0.0f,0.0f);
int count = 0,x1,y1,x2,y2;
rewind(fp);

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

while(!feof(fp) )
{
count++;
if (count>2)
{
x1 = x2;
y1 = y2;
count=2;
}
if (count==1)
{
fscanf(fp, "%d,%d", &x1, &y1);
}
else
{
fscanf(fp, "%d,%d", &x2, &y2);
printf("\n%d,%d", x2, y2);
glBegin(GL_LINES);
glVertex2i( x1, y1);
glVertex2i( x2, y2);
glEnd();
storeEdgeInTable(x1, y1, x2, y2);//storage of edges in edge table.

glFlush();
}
}

void drawDino(void)
{
initEdgeTable();
drawPolyDino(); printf("\
nTable"); printTable();

ScanlineFill();//actual calling of scanline filling..


}

void main(int argc, char** argv)


{
fp=fopen ("PolyDino.txt","r");
if ( fp == NULL )
{
printf( "Could not open file" ) ;
return;
}
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(maxHt,maxWd);
glutInitWindowPosition(100, 150);
glutCreateWindow("Scanline filled dinosaur");
myInit();
glutDisplayFunc(drawDino);

glutMainLoop();

COMPUTER GRAPHICS Lab Page


Pankaj Laddhad Institute of Technology & Management Studiedana
Department of Computer Science & Engineering

fclose(fp);
}

OUTPUT:

CONCLUSION:

In this way we have studied line algorithm.


Rajarshi Shahu College of Engineering,
Buldana

EXPERIMENT NO:-6

TITLE: Write a program to clip line using following algorithm : Cohen-Sutherland algorithm

PRIOR CONCEPT:

To Learn Cohen-Sutherland algorithm.

ALGORITHM:
Step 1 : Assign a region code for two endpoints of given line.
Step 2 : If both endpoints have a region code 0000
then given line is completely inside.
Step 3 : Else, perform the logical AND operation for both region codes.
Step 3.1 : If the result is not 0000, then given line is completely
outside.
Step 3.2 : Else line is partially inside.
Step 3.2.1 : Choose an endpoint of the line
that is outside the given rectangle.
Step 3.2.2 : Find the intersection point of the
rectangular boundary (based on region code).
Step 3.2.3 : Replace endpoint with the intersection point
and update the region code.
Step 3.2.4 : Repeat step 2 until we find a clipped line either
trivially accepted or trivially rejected.
Step 4 : Repeat step 1 for other lines
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<graphics.h>
#include<dos.h>

typedef struct coordinate


{
int x,y;
char code[4];
}PT;

void drawwindow();
void drawline(PT p1,PT
p2); PT setcode(PT p);
int visibility(PT p1,PT p2);
PT resetendpt(PT p1,PT
p2);

void main()

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

{
int gd=DETECT,v,gm;
PT p1,p2,p3,p4,ptemp;
printf("\nEnter x1 and y1\n");
scanf("%d %d",&p1.x,&p1.y); printf("\
nEnter x2 and y2\n"); scanf("%d
%d",&p2.x,&p2.y);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
drawwindow();
delay(500);
drawline(p1,p2);
delay(500);
cleardevice();
delay(500);
p1=setcode(p1);
p2=setcode(p2);
v=visibility(p1,p2);
delay(500);
switch(v)
{
case 0:
drawwindow();
delay(500);
drawline(p1,p2);
break;
case 1:
drawwindow();
delay(500);
break;
case 2: p3=resetendpt(p1,p2);
p4=resetendpt(p2,p1);
drawwindow();
delay(500);
drawline(p3,p4);
break;
}
delay(5000);
closegraph();
}

void drawwindow()
{ line(150,100,450,100
);
line(450,100,450,350);
line(450,350,150,350);
line(150,350,150,100);
}

void drawline(PT p1,PT p2)


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

PT setcode(PT p) //for setting the 4 bit code


{
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)

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

ptemp.code[3]='1'; //Left
else
ptemp.code[3]='0';
ptemp.x=p.x;
ptemp.y=p.y;
return(ptemp);
}

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);
}

PT resetendpt(PT p1,PT p2)


{
PT temp;
int x,y,i;
float m,k;
if(p1.code[3]=='1')
x=150;
if(p1.code[2]=='1')
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')
y=100;
if(p1.code[1]=='1')
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);
}

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

OUTPUT:

Before clipping

After clipping

CONCLUSION:

In this way we have studied Cohen-Sutherland algorithm .

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

EXPERIMENT NO:-7

TITLE: Write a graphics program analog clock

PRIOR CONCEPT:

To Learn Graphics.

THEORY:

 Create two rectangles, one inside the other, using the rectangle() function to act as the outer
outline of the clock & the other is the inner outline of the clock.
 Color the space between the two rectangles brown using setfillstyle() and floodfill() functions
 Implement a circle inside the inner rectangle using the circle() function
 Color all other parts leaving the circle with dark gray
using setfillstyle() and floodfill() functions.
 In the circle, insert all the digits using settextstyle() and outtextxy() functions.
 Calculate the coordinates of the digits.
 Implement the pendulum with two lines by using the line() function & another circle by using
the circle() function which will act as the bob.
 Color all of them black using the setfillstyle() and floodfill() functions again.
 Implement hour, minute & second hands by using the line() function.
 Color the objects individually by using the setcolor() function.

PROGRAM:
// C program toc draw the pendulum clock
#include <conio.h>
#include <graphics.h>
#include <stdio.h>

// Driver Code
void main()
{
int gd = DETECT, gm;

// Initialize of gdriver
initgraph(&gd, &gm, "C:\\"
"turboc3\\bgi");

// Clock Outer Outline


rectangle(500, 50, 800, 650);

// Clock Inner Outline


rectangle(520, 70, 780, 630);

// Coloring Middle Part Of


// Rectangle With Brown
setfillstyle(SOLID_FILL, BROWN);
floodfill(505, 55, 15);

// Clock Outline

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

circle(650, 200, 130);


circle(650, 200, 3);

// Coloring all the parts Of the


// clock except the circle with
// Darkgray
setfillstyle(SOLID_FILL, DARKGRAY);
floodfill(525, 355, 15);
floodfill(522, 72, 15);
floodfill(768, 72, 15);

// Inserting Digits
settextstyle(6, 0, 3);
outtextxy(697, 100, "01");
outtextxy(730, 140, "02");
outtextxy(742, 190, "03");
outtextxy(721, 240, "04");
outtextxy(690, 280, "05");
outtextxy(630, 300, "06");
outtextxy(578, 280, "07");
outtextxy(540, 240, "08");
outtextxy(530, 190, "09");
outtextxy(537, 140, "10");
outtextxy(569, 100, "11");
outtextxy(630, 80, "12");

// Left Line Of Pendulum


line(645, 328, 645, 528);

// Right Line Of Pendulum


line(655, 328, 655, 528);

// Pendulum Bob
circle(650, 546, 20);

// Coloring Line & Bob With Black


setfillstyle(SOLID_FILL, BLACK);
floodfill(652, 544, 15);
floodfill(647, 330, 15);

// Creating the Hour Hand


// & Color Blue
setcolor(BLUE);
line(647, 197, 600, 170);

// Creating Minute Hand


// & Color Yellow
setcolor(YELLOW);
line(653, 200, 730, 170);

// Creating Second Hand and the


// Color Red
setcolor(RED);
line(650, 203, 630, 290);

// Hold the screen for a while


getch();

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

// Close the initialized gdriver


closegraph();
}

OUTPUT:

CONCLUSION:

In this way we have studied a graphics program analog clock.

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering, Buldana

Department of Computer Science & Engineering

EXPERIMENT NO:-8

TITLE: Write a program to draw following type of curve-Koch curve, Bezier curves

PRIOR CONCEPT:

To Learn type of curve-Koch curve, Bezier curves.

THEORY:

What is a bezier curve?


So a Bezier curve is a mathematically defined curve used in two-dimensional graphic applications
like adobe Illustrator, Inkscape etc. The curve is defined by four points: the initial position and the
terminating position i.e P0 and P3 respectively (which are called “anchors”) and two separate
middle points i.e P1 and P2(which are called “handles”) in our example. Bezier curves are
frequently used in computer graphi cs, animation, modelling etc.
How do we Represent Bezier Curves Mathematically?
Bezier curves can be generated under the control of other points. Approximate tangents by using
control points are used to generate curve. The Bezier curve can be represented mathematically as –
Where is the set of points and represents the Bernstein polynomials i.e. Blendi ng Function
which are given by –
Where n is the polynomial order, i is the index, and u/t is the variable which has from 0 to 1.
Let us define our cubic bezier curve mathematically.
So a bezier curve id defined by a set of control points to where n is called its order(n = 1
for linear, n = 2 for quadratic, etc.). The first and last control points are always the endpoints of the
curve; however, the intermediate control points (if any) generally do not lie on the curve.
For cubic bezier curve order(n) of polynomial is 3 , index(i) vary from i = 0 to i = n i.e. 3 and u will
vary from .

Construction of a cubic Bézier curve


Rajarshi Shahu College of Engineering,
Buldana

PROGRAM:
/ C program to implement
// Cubic Bezier Curve

/* install SDL library for running thing code*/


/* install by using this commamnd line : sudo apt-get install libsdl2-dev */
/* run this code using command : gcc fileName.c -lSDL2 -lm*/

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<SDL2/SDL.h>

SDL_Window* window = NULL;


SDL_Renderer* renderer = NULL;
int mousePosX , mousePosY ;
int xnew , ynew ;

/*Function to draw all other 7 pixels present at symmetric position*/


void drawCircle(int xc, int yc, int x, int y)
{
SDL_RenderDrawPoint(renderer,xc+x,yc+y) ;
SDL_RenderDrawPoint(renderer,xc-x,yc+y);
SDL_RenderDrawPoint(renderer,xc+x,yc-y);
SDL_RenderDrawPoint(renderer,xc-x,yc-y);
SDL_RenderDrawPoint(renderer,xc+y,yc+x);
SDL_RenderDrawPoint(renderer,xc-y,yc+x);
SDL_RenderDrawPoint(renderer,xc+y,yc-x);
SDL_RenderDrawPoint(renderer,xc-y,yc-x);
}

/*Function for circle-generation using Bresenham's algorithm */


void circleBres(int xc, int yc, int r)
{
int x = 0, y = r;
int d = 3 - 2 * r;
while (y >= x)
{
/*for each pixel we will draw all eight pixels */
drawCircle(xc, yc, x, y);
x++;

/*check for decision parameter and correspondingly update d, x, y*/


if (d > 0)
{
y--;
d = d + 4 * (x - y) + 10;
}
else
d = d + 4 * x + 6;
drawCircle(xc, yc, x, y);
}
}

/* Function that take input as Control Point x_coordinates and

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

Control Point y_coordinates and draw bezier curve */


void bezierCurve(int x[] , int y[])
{
double xu = 0.0 , yu = 0.0 , u = 0.0 ;
int i = 0 ;
for(u = 0.0 ; u <= 1.0 ; u += 0.0001)

{
xu = pow(1-u,3)*x[0]+3*u*pow(1-u,2)*x[1]+3*pow(u,2)*(1-u)*x[2]
+pow(u,3)*x[3];
yu = pow(1-u,3)*y[0]+3*u*pow(1-u,2)*y[1]+3*pow(u,2)*(1-u)*y[2]
+pow(u,3)*y[3];
SDL_RenderDrawPoint(renderer , (int)xu , (int)yu) ;
}
}

int main(int argc, char* argv[])


{
/*initialize sdl*/
if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
{
/*
This function is used to create a window and default renderer.
int SDL_CreateWindowAndRenderer(int width
,int height
,Uint32 window_flags
,SDL_Window** window
,SDL_Renderer** renderer)
return 0 on success and -1 on error

*/
if(SDL_CreateWindowAndRenderer(640, 480, 0, &window, &renderer) == 0)
{
SDL_bool done = SDL_FALSE;

int i = 0 ;
int x[4] , y[4] , flagDrawn = 0 ;

while (!done)
{
SDL_Event event;

/*set background color to black*/


SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);

/*set draw color to white*/


SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);

/* We are drawing cubic bezier curve


which has four control points */
if(i==4)
{
bezierCurve(x , y) ;
flagDrawn = 1 ;
}

/*grey color circle to encircle control Point P0*/

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE);


circleBres(x[0] , y[0] , 8) ;

/*Red Line between control Point P0 & P1*/


SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderDrawLine(renderer , x[0] , y[0] , x[1] , y[1]) ;

/*grey color circle to encircle control Point P1*/


SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE);
circleBres(x[1] , y[1] , 8) ;

/*Red Line between control Point P1 & P2*/


SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderDrawLine(renderer , x[1] , y[1] , x[2] , y[2]) ;

/*grey color circle to encircle control Point P2*/


SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE);
circleBres(x[2] , y[2] , 8) ;

/*Red Line between control Point P2 & P3*/


SDL_SetRenderDrawColor(renderer, 255, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderDrawLine(renderer , x[2] , y[2] , x[3] , y[3]) ;

/*grey color circle to encircle control Point P3*/


SDL_SetRenderDrawColor(renderer, 128, 128, 128, SDL_ALPHA_OPAQUE);
circleBres(x[3] , y[3] , 8) ;

/*We are Polling SDL events*/


if (SDL_PollEvent(&event))
{
/* if window cross button clicked then quit from window */
if (event.type == SDL_QUIT)
{
done = SDL_TRUE;
}
/*Mouse Button is Down */
if(event.type == SDL_MOUSEBUTTONDOWN)
{
/*If left mouse button down then store
that point as control point*/
if(event.button.button == SDL_BUTTON_LEFT)
{
/*store only four points
because of cubic bezier curve*/
if(i < 4)
{
printf("Control Point(P%d):(%d,%d)\n"
,i,mousePosX,mousePosY) ;

/*Storing Mouse x and y positions


in our x and y coordinate array */
x[i] = mousePosX ;
y[i] = mousePosY ;
i++ ;
}
}
}
/*Mouse is in motion*/

COMPUTER GRAPHICS Lab Page


Rajarshi Shahu College of Engineering,
Buldana

if(event.type == SDL_MOUSEMOTION)
{
/*get x and y positions from motion of mouse*/
xnew = event.motion.x ;
ynew = event.motion.y ;

int j ;

/* change coordinates of control point


after bezier curve has been drawn */
if(flagDrawn == 1)
{
for(j = 0 ; j < i ; j++)
{
/*Check mouse position if in b/w circle then
change position of that control point to mouse new
position which are coming from mouse motion*/
if((float)sqrt(abs(xnew-x[j]) * abs(xnew-x[j])
+ abs(ynew-y[j]) * abs(ynew-y[j])) < 8.0)
{
/*change coordinate of jth control point*/
x[j] = xnew ;
y[j] = ynew ;
printf("Changed Control Point(P%d):(%d,%d)\n"
,j,xnew,ynew) ;
}
}
}
/*updating mouse positions to positions
coming from motion*/
mousePosX = xnew ;
mousePosY = ynew ;
}
}
/*show the window*/
SDL_RenderPresent(renderer);
}
}
/*Destroy the renderer and window*/
if (renderer)
{
SDL_DestroyRenderer(renderer);
}
if (window)
{
SDL_DestroyWindow(window);
}
}

/*clean up SDL*/
SDL_Quit();
return 0;
}

COMPUTER GRAPHICS Lab Page


Department of Computer Science & Engineering

OUTPUT:

CONCLUSION:

COMPUTER GRAPHICS Lab Page

You might also like