Lab Manual CG

27
Assignment-1 Title of Assignment:. Assignments to understand functions available in graphics library such as, a. Text and Graphics mode, initialization of graphics mode, graphics drivers, switching between text and graphics mode, error handling. b. Color, Color Palette, Aspect ratio, Text: fonts, alignment, size, orientation and justification. c. Graphics Primitives: Pixel, Line, Circle, Ellipse, Polygons, Line styles, Bar graphs, Pie Charts, Histograms, filling a polygon, windowing. Writing a Graphics Editor Relevant Theory / Literature Survey: (Brief Theory Expected) Text Editor: A text editor is a type of program used for editing plain text files. Text editors are often provided with operating systems or software development packages, and can be used to change configuration files and programming language source code. Graphics Editor : A raster graphics editor is a computer program that allows users to paint and edit pictures interactively on the computer screen and save them in one of many popular "bitmap" or "raster" formats such as JPEG, PNG, GIF and TIFF.Usually an image viewer is preferred over a raster graphics editor for viewing images.Some editors specialize in the editing of photo-realistic images such as the popular Adobe Photoshop, while others are more geared to artist- created illustrations. Graphics mode Initialization : First of all we have to call the initgraph function that will intialize the graphics mode on the computer. initigraph have the following prototype.

Transcript of Lab Manual CG

Page 1: Lab Manual CG

Assignment-1

Title of Assignment:. Assignments to understand functions available in graphics library such as,

a. Text and Graphics mode, initialization of graphics mode, graphics drivers, switching between text and graphics mode, error handling.

b. Color, Color Palette, Aspect ratio, Text: fonts, alignment, size, orientation and justification.

c. Graphics Primitives: Pixel, Line, Circle, Ellipse, Polygons, Line styles, Bar graphs, Pie Charts, Histograms, filling a polygon, windowing.

Writing a Graphics Editor

Relevant Theory / Literature Survey: (Brief Theory Expected) Text Editor:

A text editor is a type of program used for editing plain text files.Text editors are often provided with operating systems or software development packages, and can be used to change configuration files and programming language source code.

Graphics Editor :

A raster graphics editor is a computer program that allows users to paint and edit pictures interactively on the computer screen and save them in one of many popular "bitmap" or "raster" formats such as JPEG, PNG, GIF and TIFF.Usually an image viewer is preferred over a raster graphics editor for viewing images.Some editors specialize in the editing of photo-realistic images such as the popular Adobe Photoshop, while others are more geared to artist-created illustrations.

Graphics mode Initialization :

First of all we have to call the initgraph function that will intialize the graphics mode on the computer. initigraph have the following prototype.

void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);

Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system intographics mode.Initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.

*graphdriver Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics_drivers enumeration type.

*graphmode Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value

Page 2: Lab Manual CG

using a constant of the graphics_modes enumeration type.

*pathtodriver Specifies the directory path where initgraph looks for graphics drivers

(*.BGI) first.

1. If they're not there, initgraph looks in the current directory. 2. If pathtodriver is null, the driver files must be in the current directory.

*graphdriver and *graphmode must be set to valid graphics_drivers and graphics_mode values or you'll get unpredictable results. (The exception is graphdriver = DETECT.)

Graphics Primitives:

Point

Point is a graphics primitive that represents a point.

The coordinates can be given either in the ordinary form x, y or x, y, z or in scaled

form Scaled[ x, y ] or Scaled[ x, y, z ].

Points are rendered if possible as circular regions. Their diameters can be specified

using the graphics primitive PointSize.

Line

Line[ , , ... ] is a graphics primitive which represents a line joining a sequence of points.

Line can be used in both Graphics and Graphics3D (two- and three-dimensional

graphics).

The positions of points can be specified either in ordinary coordinates, as x, y or x, y,

z , or in scaled coordinates as Scaled[ x, y ] or Scaled[ x, y, z ].

Circle

Circle[ x, y , r is a two-dimensional graphics primitive that represents a circle of radius r centered at the point x, y. Circle[ x, y , , ] yields an ellipse with semi-axes and . Circle[ x, y , r, , ] represents a circular arc.

Page 3: Lab Manual CG

Angles are measured in radians counterclockwise from the positive direction.

Circle[ x, y , , , , ] yields a segment of an ellipse obtained by transforming a

circular arc with the specified starting and ending angles.

Polygon

Polygon[ , , ... ] is a graphics primitive that represents a filled polygon.

Polygon can be used in both Graphics and Graphics3D (two- and three-dimensional

graphics).

The positions of points can be specified either in ordinary coordinates as x, y or x, y,

z , or in scaled coordinates as Scaled[ x, y ] or Scaled[ x, y, z ].

The boundary of the polygon is formed by joining the last point you specify to the first

one.

Testing:

/* Sample program to draw a circle*/#include<graphics.h>#include<conio.h>main(){

int gd=DETECT,gm;initgraph(&gd,&gm,""); /* initialization of graphic mode */circle(150,150,100);getch(); closegraph(); /* Restore orignal screen mode */

}/* End of program */

Conclusion : Graphics initialization and different graphics functions are tested and used successfully.

Assignment-2

Page 4: Lab Manual CG

Title of Assignment: Write a program to implement algorithm for DDA’s line

Relevant Theory / Literature Survey: (Brief Theory Expected)

The program should make use of basic concept of DDA’s line generation algorithm.DDA’s line generation algorithm:

The DDA is a scan conversion line algorithm based on calculating Dy and Dx. We sample the line at unit intervals in one co-ordinate and determine corresponding integer values nearest the line path for the other co-ordinate.1. We will consider a line with positive slope. If the slope is less than or equal to 1,we sample it at unit x intervals (Dx = 1) and compute each successive y value as yk+1 = yk + mSubscript k takes integer values starting from 1 for the first point and increases by 1 until the final end point is reached. The value of m can be any real number between 0 and 1.

2. For lines with positive slope greater than 1, we reverse the roles of x and y. We sample at unit y intervals and calculate each succeeding x value as xk+1 = xk + 1/m

3. For the above equation we are processing the line equation from the left end point to right end point. If this processing is reversed , so either we have Dx = -1 and yk+1 = yk – m

Or

Dy = -1 and xk+1 = xk – 1/m

Use : To draw a line.

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

Algorithm:

1. Input the two line endpoints and store the left endpoint in (xa,ya).

2. Plot the first point (xa,ya).

3. Calculate constants from the two end points such as Dx and Dy for horizontal

and vertical differences .

4. The difference with the greater magnitude determines the value of parameter

steps.

Page 5: Lab Manual CG

5. We determine the offset needed at each step to generate the next pixel position

along the line path.

6. We loop through this process steps times.

7. If the magnitude of Dx is greater than the magnitude of Dy and xa<xb, the values

of increments in the x and y directions are 1 and m respectively and if the

magnitude of Dx is greater than Dy and xa>xb , the values of decrements in the x

and y directions are -1 and –m respectively.

#define ROUND(a) ((int)(a+0.5))

Void lineDDA (int xa , int ya , int xb , int yb)

{

int dx = xb – xa, dy = yb – ya , steps , k ;

Float xincr, yincr, x = xa ,y = ya;

If(abs(dx) > abs(dy)) steps = abs(dx);

xincr = dx / (float) steps;

yincr = dy / (float) steps;

Setpixel(ROUND(x),ROUND(y));

For(k=0; k<steps; k++)

{

x += xincrement;

y += yincrement;

Setpixel(ROUND(x),ROUND(y));

}

}

Page 6: Lab Manual CG

Testing:

Input :

Enter the starting point’s co-ordinates for line drawing.

200

200

Enter the ending point’s co-ordinates for line drawing

250

450

Output :

Conclusion : Thus DDA’s line generation algorithm is implemented successfully.

Assignment-3 (i)

Page 7: Lab Manual CG

Title of Assignment:. Write a program to draw a circle using Bresenhem’s circle algorithm.

Relevant Theory / Literature Survey: (Brief Theory Expected)

The program should make use of basic concept of circle generation algorithm. Bresenham’s circle generation algorithm:

This algorithm does only integer arithmetic which makes it faster than floating point. We are creating only one octant i.e. from 90 to 45 degree. We derive other seven octants of circle by symmetry property.The circle is generated by considering center point as origin with radius ‘r’.The algorithm calculates one new pixel per step.

Use : To draw a circle.

Algorithm :

1. Accept radius and center co-ordinates from user and plot first point on circumference of circle

(x,y) = (0.r)2. Calculate the initial value of decision parameter S=3-2r3. If we are using octant symmetry property to plot the pixel then until (x<y) we have to

perform following steps

If(S<=0) Update S by S=S+4x+6 and increase x by 1 Else

Update S by S=S+4(x-y)+10 and increase x by 1 and decrease y by 14. Determine the symmetry points in other octants also5. Move and calculate the pixel position (x,y) on to the circular path .

Testing:

Input :

Enter the center co-ordinates for line drawing.

320

240

Enter the radius of a circle

150

Page 8: Lab Manual CG

Output:

Conclusion : Thus Bresenham’s circle generation algorithm is implemented successfully.

Page 9: Lab Manual CG

Assignment-3 (ii)

Title of Assignment:. Write a program to draw a circle using Mid Point circle Algorithm.

Relevant Theory / Literature Survey: (Brief Theory Expected) To apply the mid point method, we define a circle function:

Fcircle(x,y) = x2 + y2 – r2

1.Any point (x,y) on the boundary of the circle with radius satisfies the equation fcircle(x,y) = 0.

2. If the point is in the interior of the circle ,the circle function is negative.

3. And if the point is outside the circle ,the circle function is positive.

4.Mid point of the circle is at (xk +1,yk).

5. We have to determine the next pixel position which is nearer to the circle either (xk + 1,yk) or (xk +1,yk -1).

6. Decision Parameter at the mid point between the two pixels :

Pk = fcircle( xk +1,yk – ½)

= (xk +1)2 + (yk -1/2)2 – r2

7.With the help of this we can calculate pk+1.

8. The initial decision parameter is obtained by evaluating the circle function at the start position (x0,y0)= (0,r)

9. p0 = 1-r.Algorithm :

1.Input radius r and circle center (xc,yc) , and obtain the first point on the circumference of the circle centered on the origin as ( x0,y0) = (0,r)2. Caculate the initial value of the decision parameter as

P0 = 5/4 – r3. At each xk position , startin at k =0,perform the following test : If pk < 0 , the

next point along the circle centered on (0,0) is (xk + 1,yk) and

Page 10: Lab Manual CG

Pk+1 = pk + 2xk+1 + 1

Otherwise , the next point along the circle is (xk +1,yk-1) and

Pk+1 = pk + 2xk+1 +1 – 2yk+1

Where 2xk+1 = 2xk +2 and 2yk+1 = 2yk -2.

4. Determine symmetry points in the other seven octants.5. Move each calculated pixel position (x,y) onto the circular path centered on

(xc,yc) and plot the coordinate values :

x= x + xc

y = y + yc

6. Repeat syeps 3 through 5 until x>=y.

Testing: Input :

Enter the center co-ordinates for line drawing.

320

240

Enter the radius of a circle

150

Output :

Conclusion : Thus Mid Point circle algorithm is implemented successfully.

Page 11: Lab Manual CG

Assignment-4

Title of Assignment: Write a program to implement algorithm for filling a polygon using scan-fill method.

Relevant Theory / Literature Survey: (Brief Theory Expected)

In contrast to boundary fill and flood fill algorithm at pixel level, this algorithm is defined at geometric level i.e. co-ordinates, edges, vertices etc.This algorithm starts with first scan line and proceeds line by line toward the last scan line and checks whether every pixel on that scan line satisfies our inside test or not, it checks which points on that scan line are inside the polygon.This method avoids the need for the seed point

Page 12: Lab Manual CG

Design Analysis / Implementation Logic:(Algorithm / Flow Chart / Pseudo Code / UML diagram / DFD as per requirement)

Algorithm:

The following function fills the polygon with the scan fill :

Void polyfill :: scanline (int xx[10],int yy[10],int col,int n)

{

int i,k,int_x[50],temp,y,ymax=0,ymin=480;

float m[50],dx,dy;

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

{

if(yy[i]>=ymax) ymax=yy[i];

if(yy[i]>=ymin) ymin=yy[i];

dx=xx[i+1]-xx[i];

dy=yy[i+1]-yy[i];

if(dx==0) m[i]=0;

if(dy==0) m[i]=1;

if(dx!=0 && dy!=0)

m[i]=(float)dx/dy ;

}

int cnt;

for(y=ymax;y>=ymin;y--)

{

cnt=0;

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

{

if((yy[i]>y&&yy[i+1]<=y)||(yy[i]<=y&&yy[i+1]>y))

{

int_x[cnt]=(xx[i]+(m[i]*(y-yy[i])));

cnt++;

}

}

for(k=0;k<cnt-1;k++)

{

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

{

Page 13: Lab Manual CG

if(int_x[i]>int_x[i+1])

{

temp=int_x[i];

int_x[i]=int_x[i+1];

int_x[i+1=temp;

}

}

}

for(i=0;i<cnt-1;i+=2)

{

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

delay(10);

}

}

getch();

}

Testing:

Input : Draw a polygon with line drawing algorithm and enter the color to fill it.

Output : Displayed the result of scan fill operation. It fills the complete polygon with

specified color.

Conclusion : The polygon filling operations have been tested and executed successfully

Page 14: Lab Manual CG

Assignment-5

Title of Assignment:. Write a program to illustrate the implementation of 2-D transformations.

Theory :

Understanding screen and Cartesian co-ordinates :

You define graphical objects in the Cartesian coordinate system by specifying the coordinates of their vertices, which are the points at which the lines that make up the object connect. For example, a triangle can be defined by three points, as shown in figure. The defining points in the triangle are (2,5), (5,2), and (2,2).

Because of the differences between a screen display and the Cartesian coordinate system,

Page 15: Lab Manual CG

you need a way to translate points from one system to the other. In graphics terms, you must map points in the Cartesian coordinate system to points in the screen coordinate system so that objects you draw onscreen are positioned correctly. Forgetting about negative coordinates for the time being, mapping point (x1,y1) in the Cartesian coordinate system to point (x2,y2) in the screen coordinate system requires the following simple formulas, shown in C++ program code

x2=y1;

y2=maxY-y1;

Because the X coordinate is unaffected by the mapping, x2 is simply assigned the value of x1. To reverse the Y coordinate, the original Y coordinate is subtracted from the window's maximum Y coordinate. For this formula to work, you must know the current size of the window.

Algorithms and requirements:

(I) Algorithm :

Using Transformation Matrices

The first step in using matrices to transform a shape is to load the matrix with the

appropriate values. What values you use and where you place them in the matrix depend on the type of transformations you're doing. A matrix that's set up to translate a shape looks like this:

1 0 00 1 0xTrans yTrans 1

Just like when you were using a formula to translate the vertices of a shape, in the preceding matrix the xTrans and yTrans variables are the number of vertical and horizontal units, respectively, that you want to translate the shape. In a program, you'd initialize this matrix like this:

MATRIX3X3 m;m[0][0] = 1.0; m[0][1] = 0.0; m[0][2] = 0.0;m[1][0] = 0.0; m[1][1] = 1.0; m[1][2] = 0.0;m[2][0] = xTrans; m[2][1] = yTrans; m[2][2] = 1.0;

A matrix for scaling a shape looks like this:

xScaleFactor 0 0

Page 16: Lab Manual CG

0 yScaleFactor 00 0 1

Here, the variable xScaleFactor is how much you want to scale the shape horizontally, whereas yScaleFactor is how much to scale vertically. In a program, you'd initialize the scaling matrix like this:

MATRIX3X3 m;m[0][0] = xScaleFactor; m[0][1] = 0.0; m[0][2] = 0.0;m[1][0] = 0.0; m[1][1] = yScaleFactor; m[1][2] = 0.0;m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 1.0;

Finally, a matrix for rotating a shape looks as follows:

cos(radians) sin(radians) 0-sin(radians) cos(radians) 00 0 1

Here, the variable radians is the angle of rotation in radians. In a program, you'd initialize the rotation matrix like this:

MATRIX3X3 m;m[0][0] = cos(radians);m[0][1] = sin(radians); m[0][2] 0.0;

m[1][0] = -sin(radians); m[1][1] = cos(radians); m[1][2] = 0.0;m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 1.0;

Multiplying 3x3 Matrices:

void MultMatrix(MATRIX3X3& product, MATRIX3X3& matrix1, MATRIX3X3& matrix2){ for (int x=0; x<3; ++x) for (int y=0; y<3; ++y) { double sum = 0; for (int z=0; z<3; ++z) sum += matrix1[x][z] * matrix2[z][y]; product[x][y] = sum; }}

(II)Initializing an Identity Matrixvoid InitMatrix(MATRIX3X3& m){

Page 17: Lab Manual CG

m[0][0]=1; m[0][1]=0; m[0][2]=0; m[1][0]=0; m[1][1]=1; m[1][2]=0; m[2][0]=0; m[2][1]=0; m[2][2]=1;}

(III)Copying a Matrix

void CopyMatrix(MATRIX3X3& dst, MATRIX3X3& src){ for (int i=0; i<3; ++i) for (int j=0; j<3; ++j) dst[i][j] = src[i][j];}

(IV)Translating with Matrices

void Translate(MATRIX3X3& m, int xTrans, int yTrans){ MATRIX3X3 m1, m2;

m1[0][0]=1; m1[0][1]=0; m1[0][2]=0; m1[1][0]=0; m1[1][1]=1; m1[1][2]=0; m1[2][0]=xTrans; m1[2][1]=yTrans; m1[2][2]=1;

MultMatrix(m2, m1, m); CopyMatrix(m, m2); }

(V)Scaling with Matrices

void Scale(MATRIX3X3& m, double xScale, double yScale){ MATRIX3X3 m1, m2;

m1[0][0]=xScale; m1[0][1]=0; m1[0][2]=0; m1[1][0]=0; m1[1][1]=yScale; m1[1][2]=0; m1[2][0]=0; m1[2][1]=0; m1[2][2]=1;

MultMatrix(m2, m1, m); CopyMatrix(m, m2);}

(VI)Rotating with Matrices

void Rotate(MATRIX3X3& m, int degrees){ MATRIX3X3 m1, m2;

Page 18: Lab Manual CG

if (degrees == 0) return;

double radians = 6.283185308 / (360.0 / degrees); double c = cos(radians); double s = sin(radians);

m1[0][0]=c; m1[0][1]=s; m1[0][2]=0; m1[1][0]=-s; m1[1][1]=c; m1[1][2]=0; m1[2][0]=0; m1[2][1]=0; m1[2][2]=1; MultMatrix(m2, m1, m); CopyMatrix(m, m2); }

Testing:

Input: Draw any polygon shape and perform the transformation with specified factors.

MATRIX3X3 m;InitMatrix(m);Translate(m, 10, 15);Scale(m, 0.5, 0.5);Rotate(m, 45);Transform(shape1, m);DrawShape(shape1);

Output: The result of all the transformations is displayed with respective factors of transformations.The code segment first declares a 3x3 transformation matrix called m. It then calls InitMatrix() to initialize m to an identity matrix. At this point, m looks like this:

1.0000000000000 0.0000000000000 0.00000000000000.0000000000000 1.0000000000000 0.00000000000000.0000000000000 0.0000000000000 1.0000000000000

The call to Translate() composes m with a translation matrix containing the values 10 and 15, which leaves m containing the translation. The transformation matrix, m, now looks like this:

1.0000000000000 0.0000000000000 0.00000000000000.0000000000000 1.0000000000000 0.000000000000010.000000000000 15.000000000000 1.0000000000000

After the call to Scale(), m contains the translation and scaling values:

0.5000000000000 0.0000000000000 0.0000000000000

Page 19: Lab Manual CG

0.0000000000000 0.5000000000000 0.000000000000010.000000000000 15.000000000000 1.0000000000000

Finally, the call to Rotate() leaves m containing the full transformation—translation, scaling, and rotation—for the shape:

0.35355339055702 0.35355339062953 0.0000000000000-0.35355339062953 0.35355339055702 0.000000000000010.000000000000 15.000000000000 1.0000000000000The call to Transform() applies the translation matrix m to all of the vertices in shape1, after which DrawShape() draws the newly transformed shape onscreen

Conclusion : All transformation options stated above are tested and executed successfully.

Assignment-6

Title of Assignment:. Write a program to implement the concept of segmentation.

Relevant Theory / Literature Survey: (Brief Theory Expected)

Theory : Segmentation

Another way of extracting and representing information from an image is to group pixels together into regions of similarity. This process is commonly called segmentation. In

2D -- we would group pixels together according to the rate of change of their intensity over a region.

3D we group together pixels according to the rate of change of depth in the

image, corresponding to pixels lying on the same surface such as a plane, cylinder, sphere etc.

Operations on segments:

Opening a segment

Once a display list is opened, you can create segments in it. A segment is a collection of elements, which are either Starbase primitive calls, attribute calls, or control

Page 20: Lab Manual CG

functions. To open a segment, use the routine open_segment

open_segment(Fieldes, segno, append, display);

where:

segno: is an integer that is uniquely associated with the segment of interest.

Append: is a boolean that specifies whether the element pointer is to be set to the end of the segment or to be left where it is. If 〈append〉 is FALSE, the element pointer is left where it was when the segment was previously closed (or at the null element if the segment hasn't been opened before); if 〈append〉 is TRUE, the element pointer is set to the last element in the segment.

Display: is a boolean that specifies whether or not the following graphics calls are to be inserted into the display list, displayed, or both. If 〈display〉 is DL_ONLY (or FALSE), the elements are merely inserted into the segment; if 〈display〉 is DL_AND_DISPLAY (or TRUE), any subsequent elements in the segment are inserted into the segment and displayed on the display device; if 〈display〉 is DISPLAY_ONLY, any subsequent elements in the segment are displayed on the display device but are not inserted into the segment.

Some things to be aware of when opening segments are as follows:

A segment must be opened prior to adding to, modifying, or inquiring its contents. Adding to a segment's contents is mentioned above: merely open a segment and do some Starbase operations. Modifying (other than just adding to) a segment, as well as inquiring a segment's contents, are discussed later.

At any one time, there can only be one open segment per display list. If you open a segment and then open another segment before explicitly closing the first one, Display List closes the first segment before opening the second.

When a segment is opened for the first time, an empty segment is created. In other words, there is nothing special you need to do to "create" a segment before you open it. If you open a segment that has not been referenced before, Display List creates a new, empty segment, and then opens it.

Closing a segment :

Closing a Display List segment is trivial:

close_segment(fildes);

There are no parameters such as append or display, because they are irrelevant to the closing operation. There is no need even for a segment number: since only one segment can be open at any one time, there can be no ambiguity as to which segment you are specifying. If there are no segments currently open, close_segment

Page 21: Lab Manual CG

is a no-op.

Renaming a segment

The first time you open a Segment model, the segments and segment groups have

assigned names that are generic, such as Segment1, Segment2, and so on. These

generic names are listed in the Segment hierarchy. The entire population for all

segments is listed in the Segment hierarchy as Population (100%).

After you have examined a segment or segment group and determined which of its

characteristics are significant, by using the summary information for the segment

and comparing it to other segments, you can give it a more descriptive name. When

you choose a new name for a segment or segment group, you must choose a name

that is unique to the Segment model.

Testing:

Input : Segments for Ex alphabets from A to Z will be displayed and any segment to make ON ( an alphabet ) will be entered.Output : The segment which is inputted will be ON and highlighted with different color.

Conclusion : Segmentation is implemented successfully

Page 22: Lab Manual CG