Top Banner
PROGRAM NO – 01 OBJECT Date…………………… TO DEVELOP THE CONCEPT OF COMPUTER GRAPHICS USING ‘C’. INTRODUCTION Computer Graphics is one of the most powerful and interesting facet of computer. There is a lot that one can do in graphics apart from drawing figures of various shapes. All video games, animations, multimedia predominantly works using Computer Graphics. This introductory too will give feeling of how some of these things are achieved using C. The aim is to make the readers comfortable with the basic concepts in graphics, Introduce themselves with standard library graphics functions and then let them explore On their own to implement certain algorithm of elementary drawing using Computer Graphics. Instead of discussing each Standard Library, graphics function in detail, most Commonly use functions and standard library files are put in the following program.
68
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Computer graphics

PROGRAM NO – 01

OBJECT Date……………………

TO DEVELOP THE CONCEPT OF COMPUTER GRAPHICS USING ‘C’.

INTRODUCTION

Computer Graphics is one of the most powerful and interesting facet of computer.

There is a lot that one can do in graphics apart from drawing figures of various shapes.

All video games, animations, multimedia predominantly works using Computer Graphics.

This introductory too will give feeling of how some of these things are achieved using

C. The aim is to make the readers comfortable with the basic concepts in graphics,

Introduce themselves with standard library graphics functions and then let them explore

On their own to implement certain algorithm of elementary drawing using Computer

Graphics.

Instead of discussing each Standard Library, graphics function in detail, most

Commonly use functions and standard library files are put in the following program.

SAMPLE PROGRAM

#include<graphics.h>

#include<conio.h>

void main()

{

int gd=DETECT,gm,x,y;

int array[]={540,220,590,270,320,510,320,490,270,540,220};

Page 2: Computer graphics

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

x=getmaxx();

y=getmaxy();

setcolor(WHITE);

rectangle(x/30+15,y/20,x/5,y/4);

outtextxy(x/30+15,y/8+5,”Rectangle”);

circle(x/2,y/6,75);

putpixel(x/2,y/6,WHITE);

outtextxy(x/2-textwidth(“Circle”)/2,y/6+10,”Circle”);

arc(x/1.2,y/6,300,90,80);

outtextxy(x/1.2,y/6,”Arc”);

line(x/30,10*y/15,x/6.10*y/15);

outtextxy(x/30+10,10*y/15+10,”Line”);

ellipse(x/2,10*y/17,0,360,100,50);

putpixel(x/2,10*y17,WHITE);

outtextxy(x/2-textwidth(“Ellipse”)/2,10*y/17+10,Ellipse”);

getch();

closegraph();

restorecrtmode();

Page 3: Computer graphics

return;

}//End of main function

DESCRIPTION OF PROGRAM

Whenever any drawing is started in graphics mode a header file ‘GRAPHICS.H’

And library file ‘GRAPHICS.LIB’ is required. The header file contains definitions and

Explanation of all the functions and constants whereas the graphics functions are kept in

The graphics library file. Both of these files are provided as part of TURBOC.

Before any drawing can be carried out, it is required to switch over to the

Graphics mode from the text mode. Switching depends on the adapter and monitor may

Be available with us. These modes have been given numbers. Out of all the modes

Available, we would like to switch over to the one which offers the best possible

Resolution.

The number of dots or picture elements or pixels available to us on the screen in

The graphics is known as the resolution. The greater the number of dots, the higher will

be the resolution. It means more the dots available clearer would be our picture.

To switch over to the graphics mode that offers the best resolution we need to call

The function initgraph(). It figures out the best resolution and puts the number

Corresponding to that mode in the variable “gm”. The ‘gm’ number tell us which monitor

We are using, and its resolution, the number of video pages it supports and the colors that

are available.

Page 4: Computer graphics

A color monitor driven by VGA adapter, the maximum resolution of which is

640 x 480 (i.e. 640 pixels from left to right and 480 pixels from top to bottom).

To understand ‘gd’ we need to understand the concept of device drivers. Device

Drivers are small programs, which talk directly to the hardware. Since we can’t be

machine dependent at any time, we need program to communicate with in a standardized

way. These programs in turn communicate with the machine. The intermediary

programs are known as device drivers.

Graphics drivers are a subset of device drivers and are applicable only in the

graphics mode. They work in the above fashion to execute whatever task we have

assigned them. TURBOC offers certain graphics drivers. These are the files with a BGI

extension. Depending on what adapter is used, one of these drivers gets selected. The

sample programs have been developed on the VGA adapter. Thus EGAVGA.BGI files

are required as graphics drivers.

In the above program ‘gd’ has been assigned the value DETECT. There by asking

Initgraph() to figure out which BGI file is needed. This file is then loaded into

Memory. If we do not initiate with DETECT macro then it is our responsibility to set up

‘gd’ and ‘gm’ with appropriate value.

The moment we change over to the graphics mode two things happens. Firstly,

The cursor disappears, since the graphics mode does not support the conventional cursor.

Secondly, a coordinate system is established whereby thetop left corner to the screen is

Page 5: Computer graphics

treated as origin (0, 0). As usual, the x – axis goes horizontally across, and the y-axis

goes vertically downward.

The basic tools we will need for drawing shapes are functions like putpixel(),

Line(), ellipse(), arc(), drawpoly() etc. All these functions have been used in the above

Sample program. Their general form is as follows:

Table 1.0 Details of the Function

SN Function Meaning

01 getmaxx() Fetches max value of x coordinate

02 getmaxy() Fetches max value of y coordinate

03 setcolor Sets the color for objects

04 rectangle() Draws rectangle using top left and right bottom

Screen coordinates

05 circle() Draws circle using x,y coordinate of center and

Radius

06 ellipse() Draw ellipse using x,y coordinate of the

Intersection of major minor axis, start angle, end

Angle, x radius and y radius

07 arc() Draws are using x,y coordinate of the center, start

Angle, end angle and radius of arc

08 Line() Draws line using end point of the line

09 drawpoly() Draws polygon using no of vedrtices and their

Coordinates

Page 6: Computer graphics

10 putpixel() Put a pixel at given location using the given color

11 outtextxy() Writes a string at the given location

Note: Two functions getmaxx() and getmaxy() have ben used in the above sample

Program, readers may change it and make user interactive before switching to the

Graphic mode imposing the limitation of the maximum resolution of given graphics

Adapter.

INPUT

OUTPUT

GRAPH

THEORETICAL QUESTIONS

1) Write the syntax of function initgraph().2) What is the significance of function initgraph()?3) What is a pixel ?4) What is maximum resolution of a VGA adapter ?5) What is the syntax of function closegraph() and why is it used ?

OBJECTIVE QUESTIONS

1) DETECT is a

a)functions b) macro c) subroutine d) procedure 2) getmaxx() fetches maximum a) x-coordinate b) y-coordinate c) z-coordinate d) r-O

Page 7: Computer graphics

coordinate 3) No of arguments passed to the function putpixel () is a)1 B)2 c)3 d) 4

4) The value of the third parameter passed to the function circle() related to

a) x-coordinate of center b) radius of circle c) y-coordinate of circle d) diameter of circle

5) To draw a rectangle which function can be used instead of rectangle () function a) circle b) ellipse c) line d) drawpoly

Page 8: Computer graphics

PROGRAM NO. 02

OBJECT Date……………....

WAP TO IMPLEMENT THE DDA LINE DRAWING ALGORITHM

ALGORITHM

An algorithm is a well-defined sequential set of mathematical and logical operations which, when implemented (or performed), produces the solution of a given mathematical problem.

In feeding numerical data and in processing – which involves implementation of algorithms and the final output of the result – two types of errors are generally introduced. They are truncation errors and rounding off errors. Besides these, errors in the implementation of the algorithm must be taken into account. (nm/6)

1. Read the line end point (x1,y1) and x2,y2) such that they are not equal. (ifEqual then plot that point and exit)

2. dx = |x2 –x1| and dy = |y2-y1|3. if (dx>=dy) then

length = dxelselength = dyendif

4. dx = (x2-x 1)/lengthdy = (y2-y1)/length

(This makes either dx or dy equal to 1 because length is either |x2-x1| or

|y2-y|. Therefore, the incremental value for either x or y is one)

5. x = x1 + 0.5* sign(dx)y= y1 + 0.5* sign(dy)(here,sign function make s the algorithm work in all quadrant. It returns-1,0,1 depending on whether its argument is <-,=0,>0 respectively. TheFactor 0.5 makes it possible to round the values in the integer function rather than truncating them).

Page 9: Computer graphics

6. i=1 (Begins the loop, in this loop points are plotted)While (i<=length){ plot (integer(x), integer (y)) x=x+dx

y=y+dyi=i+1 }

7. Stop

SAMPLE PROGRAM

#include<stdio.h>

#include<graphics.h>

#include<math.h>

main()

{

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

int i,gd,gm;

int xref=0,yref=400;

clrscr();

/*Read two end points one line

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

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

scanf(“%of”.x1);

printf(“Enter the value of y1 :\t”;

scanf(“%of,&y1)

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

scanf(“%of,&x2);

Page 10: Computer graphics

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

scanf(“%of,&y2);

/* Initialise graphics mode

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

detectgraph(&gd &gm);

initgraph(&gd,&gm””);

dx=abs(x2-xx1);

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 */

i =1; /* Initialise loop counter */

while (i<=length)

Page 11: Computer graphics

{

putpixel(x-xref,yref-y,15);

x = x+ dx;

y = y+dy;

i= i + 1:

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

Observe the line drawing process*/

}

getch();

closegraph();

}

INPUT

OUTPUT

GRAPH

THEORETICAL QUESTIONS

1. What are the merits of DDA algorithm ?2. What are the limitations of DDA algorithm ?3. Name any other line drawing algorithm4. What is aliasing ?5. Can the equation y = mx + C be used effectively to calculate

the pixel position ? Explain

OBJECTIVE QUESTIONS

1. DDA is a technique fora) Scan conversion b) Image conversion c) Graphics conversion d) All of

these……………… of a line2. Which parameter decides the selection of equation for the

calculation of coordinates in DDA algorithm.a)m b)|m| c) +m d)-m

3. The name of algorithm used for line drawing is

Page 12: Computer graphics

a) Bresenham b) Cohen sutherland c) Z-buffer d) Liang Barsky

4. DDA algorithm is faster than

a) Conventional method (y = mx + C) b) Bresenham’s Line drawing algo

c) Bresenham’s circle d) Mid point circle algo

5. Pixel position of various coordinate are calculated using

a) Absolute referencing b) Relative referencing

c) Logarithmic referencing d) Exponential referencing

Page 13: Computer graphics

PROGRAM NO. 03

OBJECT Date………………..

WAP TO IMPLEMENT BRESENHAM’S LINE DRAWING ALGORITHM

ALGORITHM

1. Read the line end points (x1,y1) and (x2,y2) such that they are not equal. (If equal thenPlot that point and exit)

2. dx =|x2-x1| and dy = |y2-y1|3. Initializing starting point

X = x1Y = y1

4. E = 2 * dy – dx(Initialize value of decision variable or error to compensate for non zero intercepts)

5. I= 1 (initialize couter)6. Plot (x,y)7. While (e>=0)

{y+1e = e-2 *dx} x= x+1 e=e+2* dy

8. 1=1+19. If (1<=dx then to step 610. Stop

SAMPLE PROGRAM

#include<stdio.h>

#include <graphics.h>

#include<math.h>

#include<dos.h>

main()

{

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

Page 14: Computer graphics

int I,gd,gm;

int xref=0,yref = 400;

clrscr();

/* Read two end points of line

………………………………….. */

printf (“Enteer the value of x1;\t);

scanf(“%of,&x1);

printf(“Enter the value of y1 :\t”):

scanf(‘%of,&y1;

printf(‘Enter the value of x2 :\t’)

scanf(‘%of &x2);

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

scanf(“%of &y2);

/* Initialise graphics mode

…………………………………*/

detectgraph(&gd,&gm);

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

dx=abs(x2-x1);

dy=abs(y2-y1);

/*Initialise starting point

…………………………….. */

x=x1;

y=y1;

/* Initialise decision variable

…………………………………. */

Page 15: Computer graphics

e=2*dy-dx;

i=1;/*Initialise loop counter */

do

{

putpixel(x-xref,yref,15);

While (e>=0)

{ y=y+1;

e=e-2 *dx;

}

x=x+1

e=e+2*dy:

i=i+1;

delay(100)

}while (i<=dx);

getch();

closegraph();

}

INPUT

OUTPUT

GRAPH

THEORETICAL QUESTIONS

1. What are the merits of Bresenham’s algorithm over the DDA algorithm?2. Write the equation of decision parameter used in Bresenham’s line drawing

algorithm.3. What are the limitations of Bresenham’s line drawing algorithm/4. Name three line drawing algorithm5. What type of calculations are used in the Bresenham’s line drawing algorithm/

Page 16: Computer graphics

OBJECTIVE QUESTIONS

1. The proposed algorithm is applicable for the range of values of ma) -1 to 1 b) 0 to 1 c) 1 to 0 d) 0 to -1

2. The line algorithm which can be generalized easily for ellipse and conica)Bresenham b)DDA c)Midpoint d) Franklin

3. Bresenham line drawing algorithm is faster than a) DDA b) Conventional method 9y = mx + C) c) Polar method d) All of these

4. The use of Bresenham algorithm avoidsa) Round Function b) Floating point addition c) Both a & b d) Either of a and b

5. Which is not a line drawing algorithma) Bresenham b) DDA c) Mid point d) End point

Page 17: Computer graphics

PROGRAM NO. 4

OBJECT Date………………...

WAP TO IMPLEMENT BRESENHAM’S CIRCLE DRAWING ALGORITHM

ALGORITHM

1. Read the radius ® of the circle.2. d =3-2r(Initialize starting point)

3. x=0 y=r (Initialize starting point)

4. Do

{Plot (x,y)

If (d<0) then{ D = d+4x+6}Else{ d=d+4(x-y)+10

Y=y-1}

X=x+1While (x<y)

5. Stop

SAMPLE PROGRAM

#include<stdio.h>

#include<graphics.h>

#include<math.h>

void main()

{

float d;

Page 18: Computer graphics

int gd,gm,x,y;

int r,tim;

clrscr();

/*Read the radius of the circle

………………………………. */

printf(“Enter the radius of a circle :”);

scanf(“%d”,&r);

printf(“Enter the Time delay (milli second):”);

scanf(“%d”,&tim);

/*Initialise graphics mode

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

detectgraph(&gd,&gm);

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

/*Initialise starting points

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

x = 0 ;

y = r ;

/*initialise the decision variable

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

d = 3 – 2 *r;

do

{ putpixel(200+x,200+y,15);

putpixel(200+x,200+y,15);

putpixel(200+y,200+x,15);

putpixel(200+y,200-x,15);

Page 19: Computer graphics

putpixel(200+x,200-y,15);

putpixel(200-x,200-y,15);

putpixel(200-y,200-x,15);

putpixel(200-y,200+x,15);

putpixel(200-x,200+y,15);

if(d<=0)

{

d=d+4*x+6;

}

Else

{

d =d+4*x+6;

}

d=d+4(x-y)+10;

y= y-1;

}

x = x+1;

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

observe the line drawing process */

}

while(x<y);

getch();

closegraph();

return;

}

Page 20: Computer graphics

Note:- The algorithm plots 1/8 of the circle.

INPUT

OUTPUT

GRAPH

THEORETICAL QUESTIONS

1. What is the generalized equation of a circle with center at origin and radius ‘r’ ?2. Write trigonometric equation to draw a circle.3. What is the difference between Bresenham’s circle drawing algorithm and other

Conventional equations?4. Name any other algorithm for circle drawing.5. Write the equation of decision parameter for circle drawing using Bresenham’s

Circle drawing algorithm?

OBJECTIVE QUESTIONS

1. In the above algorithm pixel positions are calculated for a) Semi-quarter circle b) Quarter circleb) Half circle d) Full circle

2. Which not a circle drawing algorithma)Bresenham b) DDA c) Mid point d) Franklin

3. To draw complete circle using Bresenham’s circle drawing algorithm

a) 8 – way symmetry b) 4 – way symmetry

c) 2 – way symmetry d) 1-way symmetry

4. The above method generates the pixel position for a circle having it center at

a) Origin b) x-axis c) y-axis d) At the center of reference frame

5. Which of the following transformation may be required to calculate the pixel

Position of the circumference of a circle whose center is not at origin

a) Flip b) Move c) Rotate d) Scale

Page 21: Computer graphics

PROGRAM NO. 05

OBJECT Date………………………

WAP TO IMPLEMENT MID – POINT CIRCLE DRAWING ALGORITHM

ALGORITHM

u

1. Read the radius ® of the circle2. Initialize starting position as

x = 0 y = 0

3. Calculate initial value of decision parameter as P = 1.25 – r

4. do{ Plot(x,y) If (d <0) {

x = x + 1y = yd = d + 2x + 1

else {

x = x + 1y = y – 1d = d + 2x + 2y + 1

}while (x <y)

5. Determine symmetry points6. Stop

SAMPLE PROGRAM

#include<stdio.h>

#include<graphics.h>

#include<math.h>

main()

{

Page 22: Computer graphics

float p;

int i,gd,gm,x,y;

int r;

/* initialize graphics

……………………….. */

detectgraph(&gd,&gm);

initgraph(&gd,gm,””);

/* Read the radius

……………………. */

printf(“Enter the radius of the circle ;”);

scanf(“%d”,&r);

x=0;

y=r;

p=1.25 – r;

do

{

putpixel(200+x,200+y,15);

putpixel(200+y,200+x,15);

putpixel(200+x,200-y,15);

putpixel(200+y, 200-y,15);

putpixel(200-x,200-y,15);

putpixel(200-x,200+y,15);

putpixel(200-y,200+x,15);

putpixel(200-y,200-x,15);

if (p < 0)

Page 23: Computer graphics

{

x+ x+1;

y=y

p=p+2*x + 2;

}

else

{

x =x+1

y=y-1

p=p+2*(x-y)+1;

}

delay(10000);

}

while(x <y);

getch();

closegraph();

}

INPUT

OUTPUT

GRAPH

THEORETICAL QUESTION

1. What is Staircase effect?2. Write the equation of decision parameter used in Mid-Point circle drawing algorithm3. What is the difference between this and Bresenham’s circle drawing algorithm?4. Name the method is used to draw a full circle in mid-point circle drawing algorithm?5. Name any two circle drawing algorithm.

Page 24: Computer graphics

OBJECTIVE QUESTIONS

1. The pixel positions calculated using this and Bresenham’s circle algorithm area) Exactly same b) Different c) Partially different d) Depends on origin selection

2. Which of the following algorithm can be easily extended to ellipse and conic sectionsa) Mid-Point b) Bresenham c)DDA d) All of these

3. The ill effects of the scan conversion is removed bya) Anti-aliasing b) aliasing c) Staircase d) Jaggies

4. The functional value at the mid point between two pixels is evaluated to determine whichPixel out of the two should be plotted in

a) Bresenham b) DDA c) Mid-point d)Hodgman algorithm5. Which is not a method of Anti-aliasing

a) Increrasing resolution b) Weighted are sampling c) pixel phasing d) Decreasing resolution.

Page 25: Computer graphics

PROGRAM NO.06

OBJECT Date ………………..

WAP TO DRAW BEZIER CURVE

ALGORITHM

1. Read no control points2. Read the coordinate of control points3. Generate Parametric equation to calculate4. A) x – coordinate of the curve5. B)y – coordinate of the curve6. Using the Generalized equation for the Bezier curve7. Select suitable increment in the parameter ‘u’.8. Iterate to get the various points of curve using equation 3a) and 3b).9. Store the points in array10. Plot the points.11. Stop

The Generalized Parametric Equation of the Bezier Curve is

Where

1. 0< = u <=12. N = Degree of Polynomial3. n =No of control points4. N=n-15. Pk = The x/y coordinate of control Point.

SAMPLE PROGRAM

#include<stdio.h>

#include<dos.h>

#include<graphics.h>

#include<conio.h>

#include<process.h>

#include<iostream.h>

Page 26: Computer graphics

#include<math.h>

void Init Graph();

void Draw Point (int x, int y, int clr);

double fact (double x);

void main()

{

int i,k,counter;

float u,incr,factor;

/*

float Px[5]={60,80,150,180,0};

float Py[5]={20,100,90,50,0};

*/

/*

//Parabola

floatPx[5]={9,0,9,180,0}

float Py[5]={-6,0,6,50,0};

*/

//Circle

float Px[11]={10,8,6,7,0,-7.07,-10,-7.07, 0,7.07,8.6,10};

float Py[11]={0,5,7.07,10,7.07, 0,-7.07,-10,-7.07,-5,0}

//Give Due care to Control Points

int ctrl-pt;

float tPx,tPy;

Page 27: Computer graphics

int Xo,Yo;

float Sx,Sy;

FILE *fp;

Clrscr();

//Variable initialization

Incr = 0.01; ctrl –pt=11; Sx=15; Sy=15;

tPx=Px[0]; tPy=Py[0]; counter=1;

xo=100; Yo=250;

fp=fopen(“bzr.txt”,”w”)

// Note we are initializing the tPx and tPy with the starting value of the

//control point because pow(0,0)give domain error and also it is useless

//to do calculation for the first point

//End of variable initialization

Ctrl pt--; //Because counting starts from zero;

Init-Graph();

for u=incr; u<=1; u+=incr)

{

fprintf(fp,”%4d X=%8.2f| Y=%8.2f\n”,counter++,tPx,tPy);

Draw Point (Xo+Sx*tPx,Yo-Sy*tPy,9);

tPx=0; tPy=0 //Resetting the tPx,tPy for the next calculation

for9K=0; k<=ctrl-pt; k++)

{

Factor=fact(ctrl-pt)/(fact(k) * fact(ctrl-pt-k));

Page 28: Computer graphics

tPx+=factor*pow(u,k) *Px[k]* pow(1-u),(ctrl-pt-k));

tPy+=factor*pow(u,k)*Py[k]* pow(1-u),(ctrl-pt-k));

}//End of inner for loop

}//End of outer for loop

fclose(fp);

getch();

return;

}//End of the main

double fact(double x)

{

If (x<1)

Return 1;

double factorial;

factorial = x

while (x > 1)

factorial = factorial*(--x);

return factorial;

}//End of the function

void Init-Graph()

{

int xmax,ymax,

int gdriver = DETECT, gmode, errorcode;

/*initialize graphics and local variables */

Page 29: Computer graphics

initgraph(&gdriver,&gmode,”c.\\turboc\\”);

/*read result of initialization */

errorcode = graphresult();

/*an error occurred */

If (errorcode !=grOk)

{

printf(“Graphics error: %s\n”, grapherrormsg(errorcode));

printf(“Press any key to halt:”);

getch();

exit(1);

}

setbkcolor(0);

return;

}

void Draw Point (int x, int y, int clr)

{

putpixel(x,y,clr);

putpixel(x+1,y,clr);

putpixel(x-1,y,clr);

putpixel(x,y-1clr);

putpixel(x,y+1,clr);

}

INPUT

OUTPUT

Page 30: Computer graphics

GRAPH

THEORETICAL QUESTIONS

1. What are the properties of Bezier curve?2. What is the difference between the Bezier curve and Splines?3. Write the parametric equation for ellipse, parabola and hyperbola.4. Write the parametric equation of Bezier curve using four control points5. Write the Generalized parametric equation for Bezier curve.

OBJECTIVE QUESTIONS

1. Bezier curve always passes througha) First and last control point b)First and second control point

c)Only mid control point d) Any control point except mid

2. The relation between degree of polynomial (DOP) and the no of control points (noc) is

a) DOP=noc+1 b) DOP = noc-1 c)DOP=In(noc) d) DOP =noc

3. The no.of control points in a cubic Bezier curve will be

a)1 b)2 c)3 d)4

4. The two basic type of parametric curves are

a) Interpolation and approximation b) Extrapolation and approximation

c) Interpolation and extrapolation d)Approximation & substraction

5. Bezier curve is an example of

a) Interpolation b)Approximation c)Extrapolationd)Substraction

…………type of parametric curve.

Page 31: Computer graphics

PROGRAM NO.07

OBJECT Date…………………

WAP TO IMPLEMENT COHEN SUTHERLAND LINE CLIPPING ALGORITHM

ALGORITHM

1. Read two end points of the line say P1(x1,y1) and P2(x2,y2).2. Read two corners (left-top and right bottom) of the window, say (Wx1,Wy1 and

Wx2,Wy2).3. Assign the region code for two end points P1 and P2 using following steps

; Initialize code with bits 0000

Set Bit 1 – if (x < Wx1)

Set Bit 2 – if (x > Wx2)

Set Bit 3 – if (y < Wy2)

Set Bit 4 – if (y > Wy1)

4. Check for visibility of line P1 P2a) If region codes for both tow endpoints P1 and P2 are zero then

the line is completely visible. Hence draw the line and go tostep 9.

b) If region codes for endpoints are not zero and the logicalANDing of them is also nonzero then the line is completelyInvisible, so reject the line and go to step 9.

c) If region codes for two endpoints do not satisfy the conditions in 4a) and 4b) the line is partially visible.

5. Determine the intersecting edge of the clipping window by inspecting the region codes oftwo endpoints.

a) If region codes for both the end points are non zero, findIntersection points P1’ and P2’ with boundary edges of clippingwindow with respect to point P1 and Point2 respectively.

b) If region code for any one end point is non zero then findIntersection point P1 or P2’ with the boundary edge of theClipping window with respect to it.

6. Divide the line segment considering intersection points

Page 32: Computer graphics

7. Reject the line segment if any one end point of it appears outside the clipping window.

8. Draw the remaining line segment.9. Stop.

SAMPLE 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 draw window ()

void draw line (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;

Page 33: Computer graphics

intigraph(&gd,gm,””)

cleardevice();

printf(“\n\n\t\t\ENTER END POINT 1 (x,y):”);

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

printf(“n\n\t\t ENTER END POINT 2 (x,y):”);

scanf(“%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);

Page 34: Computer graphics

p2=resetendpt(p2,p1);

drawwindow();

drawline(p1,p2,15);

break;

getch();

closegraph();

return(0);

}

/*Function to draw window */

void drawwindow()

{

/*Function to draw line between two points

……………………………………………………….*/

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

{

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

Page 35: Computer graphics

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

}

/*Function to set code of the coordinates

…………………………………………………………..*/

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;

Page 36: Computer graphics

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(pl.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 (T p1,PT p2)

Page 37: Computer graphics

{

PT temp;

int x,y,I;

float m,k;

if (pl.code[3]=’1’/*Cutting LEFT Edge */

x=150;

If(pl.code[2]=’1’)/*Cutting RIGHT Edge */

x=450

If(pl.code[3]=’1’)||(pl.code[2]=’1’))

{

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

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

temp.y=k;

temp.x=x;

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

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

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

return(temp);

}

If (p1.code[0]=’1’)/*Cutting TOP Edge */

y=100;

if(pl.code[1[=’1’)/* Cutting BOTTOM Edge */

y=350;

Page 38: Computer graphics

{

If(pl.code[0]=’1)||(pl.code[1]=1))

{

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

k=(float)pl.x+(float)(y-pl.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

GRAPH

THEORETICAL QUESTIONS

1. What is point clipping ?2. What is line clipping ?3. Name any two line clipping algorithm ?4. What is Region code or Outcodes ?5. What is Scissoring ?

Page 39: Computer graphics

OBJECTIVE QUESTIONS

1. The process of selecting and viewing the picture with different views is calleda) Windowing b) Clipping c) Normalizing d) Viewing

2. A process which divides each element of the picture into its visible and invisibleportion, allowing the invisible portion to be discarded is calleda) Windowing b) Normalizing c) Clipping d) Viewing

3. Cohen-Sutherland’s 2D line clipping approach is aa)Parametric approach b) Non-Parametric approachc)Geometric approach d)Logarithmic approach

4. The no of bit used to generate Outcode for a given coordinates are

a) 2 b)4 c)6 d)8

5. Cohen Sutherland line clipping algorithm computes the Outcode of

a) End Points b) Mid point c) Any two consecutive point

d)Both a and b …..of a line

Page 40: Computer graphics

PROGRAM NO.08

OBJECT Date………………

WAP TO IMPLEMENT MID POINT SUB-DIVISION LINE CLIPPING ALGORITHM

ALGORITHM

1. Read two end points of the line say P1(x1,y1) and P2(x2,y2)2. Read two corners (left – top and right bottom) of the window, say (Wx1, Wy1 and

Wx2,Wy2).3. Assign region codes for two end points using following steps:

Initialize code with bits 0000

Set Bit 1 - if (x<Wx1)

Set Bit 2 - if (x> Wx2)

Set Bit 3 - if (y< Wy1)

Set Bit 4 - if (y> Wy2)

4. Check for visibility of linea) If region codes for both endpoints are zero then the line is completely visible.

HenceDraw the line and go to step 6.

b) If region codes for endpoints are not zero and the logical ANDING of them is alsoNon-zero then the line is completely invisible, so reject and the line and go to step 6.

c) If region code for two endpoints do not satisfy the conditions in 4a) and 4b) the line isPartially visible.

5. Divide the partially visible line segment in equal parts and repeat steps 3 through 5 for bothSubdivided line segments until you get completely visible and completely invisible line segments.

6. Stop.

Page 41: Computer graphics

SAMPLE 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 */

Typed of 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, PTp2);

PT resetendpt(

main()

{

Int gd=DETECT,gm,v.

PT p1,p2,ptemp;

Page 42: Computer graphics

intigraph(&gd,gm,’’);

cleardevice();

printf(‘n\n\t\t\ENTER END POINT 1(x, y”);

scanf(“%d,%d”.&p1,x,&pl.y);

printf(“\n\n\t\ENTER END POINT 2 (x, y):”)

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

cleardevice()

drawwindow();

getch();

drawwindow()

midsub(p1,p2);

getch();

closegraph();

return(0);

}

midsub(PT p1,PT p2)

{

PT mid;

int v;

p1=setcode(p1)

p2=setcode(p2);

v=visibility(p1,p2);

switch(v)

Page 43: Computer graphics

{

case 0;/*Line completely visible *//

drawline(p1,p2,15);

break;

case 1: /* Line completely invisible */

break;

case 2: /* line partly visible */

mid.x=p1.x + (p2.x-p1.x)/2;

mid.y=p1.y + (p2.y-p1.y)/2;

midsub(p1,mid);

mid.x=mid.x+1:

mid.y=mid,y+1;

midsub(mid,p2);

break;

}

}

/*Function to draw window */

void drawwindow()

{

setcolor(RED);

line(150,100,450,100);

line(450,100,450,400);

Page 44: Computer graphics

line(450,400,150,400);

line(150,400,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 coordinates

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

PT setcode(PT p)

{

PT ptemp;

if(p.y<=100)

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

else

ptemp.code[0]=’0’

if(p.y>=400)

ptemp[1]=’1’;/*BOTTOM*/

else

ptemp.code[1]=’0’

if(p.x>=450)

Page 45: Computer graphics

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

Page 46: Computer graphics

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

}

INPUT

OUTPUT

GRAPH

THEORETICAL QUESTIONS

1. What is Mid Point line clipping algorithm ?2. What are the various type of coordinates ?3. Which method is used to clip circle and ellipse by taking their extents.4. Which line clipping algorithm is applicable only for the convex window region.5. What is window and viewport ?

OBJECTIVE QUESTIONS

1. The Mid Point Subdivision algorithm is a special case ofa) Liang Berksy b) Brute – Forceb) Cohen Sutherland d) Sutherland & Hodgman

2. Clipping is donea) Before scan conversion b)After scan conversion

c)In mid way d) Any of these

3. The combination of Clipping Scan conversion is known as

Page 47: Computer graphics

a) Scissoring B) Viewing c) Windowing d) Normalizing

4. Which is not line clipping algorithm

a)Cohen – Sutherland b) Mid point Subdivision c) Z-Buffer d) Liang – Barskey

5. Which is more efficient than Cohen Sutherland line clipping algorithm

a) Mid-Point Subdivision b) Liang – Barksey

c) Brute – Force d) Sutherland – Hodgman

Page 48: Computer graphics

PROGRAM NO – 09

OBJECT Date …………………….

WAP TO MULTIPLY TWO GIVEN MATRICES

ALGORITHM

1. Initialize First Matrix let it be A(m)(n).2. Read the order of First Matrix, let m=3,n=33. Input Data to the elements of the First Matrix4. Initialize Second Matrix let it be (q)(r)5. Read the order of Second Matrix, let q=3,r=36. Input Data elements of the Second Matrix7. Check the Possibility of Multiplication between two matrices8. If possibility exists apply the following formula9. C(i)(j)=c(i)(j) + a(i)(k) * b(k)(j)

And Store the values into a New matrix, let it be C(m)(r)10. Otherwise terminate the program messaging that multiplication is not possible.11. Print the Result on Console.12. Stop.

SAMPLE PROGRAM

# include<stdio.h>

#include<conio.h>

void main()

{

Int i,j.k;

int a[3][3],b[3][3],c[3][3];

clrsr();

printf(“Enter values for the First Array ROW WISE \n”);

Page 49: Computer graphics

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

{

printf(“Enter value for a [%d][%d]=”,i+1,j+1);

scanf(“%d”,&a[i][j]);

}//End of inner for loop

}

printf(“enter values for the Second Array ROW WISE \n”);

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

{

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

{

printif(“Enter value for a {%d}[%d]=”.i+1.j+1;

scanf(%d”,&b[i][j];

} //End of inner for loop

}

printf(“\n\n\”);

//Multiplication of Above Two Array and Storing the values into another Array C

printf(Multiplication of the above Two Matrices is \n\n”);

printf(“******************************************************************************\

n\n\n”);

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

{

c[i][j]=0

Page 50: Computer graphics

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

{

C[i][j]=c[i][j] + a[i][k] * b[k][j];

}

}

}

//printing of the Multiplied array

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

{

//printing of Array A[i][j]

printf (“|”);

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

{

printf(“%5d”,a[i][j];

}

printf(“|”);

If(i==0)

printf(“*”);

else

printf(“”);

//Printing of Array B[i][j]

printf(“|”)

for(j=0;j<3;J++)

Page 51: Computer graphics

{

printf (“%5d”,b[i][j][j];

}

printf(“|”);

//Printing of Array C[i][j]

If (i==0)

printf(“ =”);

Else

printf(“ “);

printf(“ | “);

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

{

printf(“%5d”,c[i][j]);

}

printf(“|\n”);

}//End of Outer for loop

printf(“\n\n\n”****************************************************************************\n\n\n”);

gotoxy(1,48);

printf(“Press Any Key to Continue….”);

getch();

return;

Page 52: Computer graphics

}//End of the Main()

INPUT

OUTPUT

THEORETICAL QUESTIONS

1. What is Subscripted Variable ?2. What is One dimensional array variable ?3. What is Two Dimensional array variable ?4. What is the necessary condition for the two Matrix to be Multiplied ?5. What is the use of Matrix ?

OBJECTIVE QUESTIONS

1. The declaration of an array variable like A[10] is an example of a) 1 b)2 c)3 d)4

….dimensional array.2. The declaration of an array variable like B[10][10] is an example of

a)1 b)2 c)3 d)4…. Dimensional array.

3. The declaration of an array variable like C[10][10] is an example of a)1 b)2 c)3 d)4

……dimensional array.

4. The no.of elements in the variable declaration like intA[5] will bea)2 b)5 c)4 d)10

5. The no.of elements in the variable declaration like int A[5][5] will be a)10 b)25 c)20 d)50

Page 53: Computer graphics

PROGRAM NO-10

OBJECT Date………………………

WAP TO DRAW CUBIC SPLINE

ALGORITHM

1. Initialize the values of coefficients2. Initialize the value of parameter u,3. Set a proper increment4. Calculate the coordinate of various points using the parametric equation of CUBIC

SPLINEi.e

X=a0 + a1 * u + a2 * u2 +a3 * u3 andY= b0 + b1 * u + b2 * u2 + b3 * u3

5. Plot the different values on the graphics mode6. Stop

SAMPLE PROGRAM

# include < stdio.h>

#include<conio.h>

#include<dos.h>

#include<process.h>

#include<graphics.h>

#include<math.h>

Void initialize – Graphics();

Void Draw _ Axis(int dx,int dy);

Int datum_y=450;

Page 54: Computer graphics

Int datum _x=10;

//Start of the main()

void main()

{

float a[4];

float b[4];

float x,y;

printf(“Enter the value of Coefficients for x Co-ordinate\n”);

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

{

printf(“Enter the value of a(%d) = “.a[i];

scanf (“% of”,&a[i]);

}

printf (“Enter the value of Coefficients for y Co-ordinate \n”);

/* initialize graphics mode */

initgraph (&gdriver,&gmode,”d;\\tcc”);

/*read result of initialization */

Errorcode = graphresult();

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

{

printf (“Graphics error: %s\n\”, grapherrorms(errorcode));

Page 55: Computer graphics

printf(“Press any key to halt:”);

getch();

exit(1); /* return with error code */

}

/*draw a line */

outtextxy(250,40,”CUBIC SPLINE”);

/* clean up */

}

void Draw_Axis(int dx, int dy)

{

for(int i=0;i<620,i++)

putpixel(dx+i,dy,WHITE); //Draw Horizontal Line

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

putpixel(dx,dy-i,WHITE); //Draw Vertical Line

return;

}

INPUT

OUTPUT

GRAPH

THEORETICAL QUESTIONS

1. What is a Cubic Spline ?2. What are the applications of the Cubic Spline ? 3. What is the range of value of parameter ‘u’ in case of Cubic Spline?4. How it is different from Bezier Curve?

Page 56: Computer graphics

5. How multisegment Cubic Splines are made ?

OBJECTIVE QUESTIONS

1. The value of parameter ‘u’ in case of cubic spline will beA1 b)2 c)3 d)4

2. No.of Control points in a Cubic Spline isa)1 b)2 c)0 d)4

3. The equation y = a0 + a1 * X2 +a3 *X3 is

a)Cartesian b) Polar c)Parametric d)Complex

… form of equation.

4.The equation y=y= a0 +a1 * X +a2 * X2 + a3 *X3, where X is a parameter

………………………………is a

a) Cartesian b) Polar c) Paramertic d)Complex…………………….. form of equation.

5. Y=a1 + a2 X + a3 X2 is the equation of

a) Slope b) Normal c) Asymptote None of these

of a Cubic Spline.