You are on page 1of 76

DETAILED SYLLABUS

5CS4-21 COMPUTER GRAPHICS & MULTIMEDIA LAB

Class: VI Sem. B.Tech. Branch: CSE


Schedule per Week Practical Hrs.: 2
Examination Time = Four (4) Hours Maximum Marks =
50 [Sessional /Mid-term (30) & End-term (20)]

1 Implementation of Line, Circle and ellipse attributes.

2 To plot a point (pixel) on the screen

3 To draw a straight line using DDA Algorithm

4 Implementation of mid-point circle generating Algorithm


5 Implementation of ellipse generating Algorithm
6 Two Dimensional transformations - Translation, Rotation, Scaling, Reflection, Shear
7 Composite 2D Transformations
8 Cohen Sutherland 2D line clipping and Windowing
9 Sutherland – Hodgeman Polygon clipping Algorithm
10 Three dimensional transformations - Translation, Rotation, Scaling
11 Composite 3D transformations
12 Drawing three dimensional objects and Scenes
13 Generating Fractal images

Page | 1
List of Experiments

Exp.
Name of Experiment Page No.
No
Introduction to computer graphic: bitmapped and vector/structured.
1 9
To produce a single pixel and pre specified pattern on screen:

To implement features like changing background color, fore ground


2 17
color, resizing window, repositioning of window.

3 Write a program to implement Bresenham Line algorithm. 21

4 Write a program to implement DDA Line algorithm. 26


5 Write a program to implement midpoint circle algorithm. 31
6 Write a program to fill an ellipse. 35
7 Write a program to fill a polygon. 38
8 Write a program to hoist a flag. 42
9 Write a program to create balloons. 51
10 Write a program to implement a walking robot. 54
11 Write a program to implement a rotating wheel. 61

12 Write a program to implement Cohen Sutherland algorithm. 67

Page | 2
DO’S AND DONT’S

DO’S
1. Student should get the record of previous experiment checked before starting the new
experiment.
2. Read the manual carefully before starting the experiment.
3. Before starting the experiment, get circuit diagram checked by the teacher.
4. Before switching on the power supply, get the circuit connections checked.
5. Get your readings checked by the teacher.
6. Apparatus must be handled carefully.
7. Maintain strict discipline.
8. Keep your mobile phone switched off or in vibration mode.
9. Students should get the experiment allotted for next turn, before leaving the lab.

DONT’S
1. Do not touch or attempt to touch the mains power supply Wire with bare hands.
2. Do not overcrowd the tables.
3. Do not tamper with equipment’s.
4. Do not leave the without permission from the teacher.

Page | 3
INSTRUCTIONS TO STUDENTS
Before entering in the lab
 All the students are supposed to prepare the theory regarding the next experiment /Program.
 Students are supposed to bring their lab records as per their lab schedule.
 Previous experiment/program should be written in the lab record.
 If applicable trace paper/graph paper must be pasted in lab record with proper labeling.
 All the students must follow the instructions, failing which he/she may not be allowed in the
lab.

While working in the lab


 Adhere to experimental schedule as instructed by the lab in-charge/faculty.
 Get the previously performed experiment/ program signed by the faculty/ lab in charge.
 Get the output of current experiment/program checked by the faculty/ lab in charge in the
lab copy.
 Each student should work on his/her assigned computer at each turn of the lab.
 Take responsibility of valuable accessories.

Page | 4
Department of computer Science & Engineering
List of Program Educational Objectives (PEO)

Graduate students will have thorough knowledge in science and engineering

PEO-1 disciplines and have broad-based education in areas of computer science,


including theoretical foundations, algorithms data structures and hardware.

Graduates will have solid foundation in engineering field required to solve

PEO-2 computing problems using various programming languages and software’s/tools,


and students can solve problems through logical and analytical thinking.

Graduates will be trained with good engineering breadth so as to comprehend,


PEO-3
analyze, design, and create novel products and solutions for the real life problem.

To develop the professional and ethical attitude, effective communication skills,

PEO-4 teamwork skills, multidisciplinary approach, and an ability to relate engineering


issues to broader social context.

Graduates will be provided with an academic environment to peruse excellence in


leadership, teamwork and lifelong learning needed for successful professional
PEO-5
career through independent self-studies, projects, thesis and through internships
etc.

Page | 5
List of Program Outcomes
Engineering Knowledge: Apply knowledge of mathematics and science,
PO-1 with fundamentals of Computer Science & Engineering to be able to solve
complex engineering problems related to CSE.
Problem Analysis: Identify, Formulate, review research literature and
PO-2 analyze complex engineering problems related to CSE and reaching
substantiated conclusions using first principles of mathematics, natural
sciences and engineering sciences.
Design/Development of solutions: Design solutions for complex
engineering problems related to CSE and design system components or
PO-3 processes that meet the specified needs with appropriate consideration for
the public health and safety and the cultural societal and environmental
considerations.
Conduct Investigations of Complex problems: Use research–based
PO-4 knowledge and research methods including design of experiments, analysis
and interpretation of data, and synthesis of the information to provide valid
conclusions.
Modern Tool Usage: Create, Select and apply appropriate techniques,
PO-5 resources and modern engineering and IT tools including prediction and
modeling to computer science related complex engineering activities with
an understanding of the limitations.
The Engineer and Society: Apply Reasoning informed by the contextual
PO-6 knowledge to assess societal, health, safety, legal and cultural issues and
the consequent responsibilities relevant to the CSE professional
engineering practice.
Environment and Sustainability: Understand the impact of the CSE
professional engineering solutions in societal and environmental contexts
PO-7
and demonstrate the knowledge of, and need for sustainable development.

Ethics: Apply Ethical Principles and commit to professional ethics and


PO-8
responsibilities and norms of the engineering practice.

Individual and Team Work: Function effectively as an individual and as


PO-9
a member or leader in diverse teams and in multidisciplinary Settings.

Page | 6
Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large such as
PO-10 able to comprehend and with write effective reports and design
documentation, make effective presentations and give and receive clear
instructions.
Project Management and Finance: Demonstrate knowledge and
understanding of the engineering management principles and apply these to
PO-11 one’s own work, as a member and leader in a team, to manage projects and
in multi-disciplinary environments.

Life-Long Learning: Recognize the need for and have the preparation and
PO-12 ability to engage in independent and life-long learning the broadest context
of technological change.

List of Program Specific Outcomes (PSO)


Knowledge Enhancement in Computing: The ability to interpret the
foundation and strategy of hardware and software of computer systems.
PSO-1 Graduates can solve the problems in the areas related to algorithms,
multimedia, data analytics, cloud computing, human computer interface,
robotics, artificial intelligence and networking for efficient design of
computer systems.
Software Design and Development: The ability to understand the software
development lifecycle and methodologies of software systems. Graduate
PSO-2 will learn competent skills and knowledge of software design process.
Graduate will be acquaintance to practical proficiency with a broad area of
programming concepts.

Page | 7
Course Outcomes:
Upon successful completion of this Computer Graphics & Multimedia Lab course Students
should be able to:
CO-1: Able to define basics of Computer Graphics, display devices along with output primitives
CO-2: Able to Outline various 2D, 3D geometric transformations and viewing.
CO-3: Able to Compare and Contrast various object representation.
CO -4: Able to List various algorithms to detect hidden surfaces and rendering.
CO -5: Able to Create animation scenes.

Course Outcomes to Program Outcomes Mapping:

Program Outcomes PSO’s


Course
PO PO PO PO PO PO PO PO PO - PO PO PO
Outcomes PSO -1 PSO -2
–1 –2 -3 -4 -5 -6 -7 –8 9 -10 -11 -12
CO-1 - 2 - - - - - - - - - 2 2 -
CO-2 2 2 2 - 2 - - - - - - 2 2 -
CO-3 2 2 2 - 2 - - - - - - 2 2 -
CO-4 2 2 - - 2 - - - - - - 2 2 -
CO-5 2 2 2 - 2 - - - - - - 2 2 -

Note: Correlation levels 1, 2 or 3 as defined below:


1: Slight (Low)2: Moderate (Medium)3: Substantial (High)

Page | 8
INTRODUCTION TO COMPUTER GRAPHICS

There are basically two types of computer graphic, bitmapped and vector/structured.

Bitmap:-

Bitmapped graphics are images that are mapped to the monitor or screen. The screen is made up
of tiny dots called pixels. These dots can display various colours depending on the type of
computer hardware and software you have. Using shades of red, green and blue (RGB) an image
can be displayed on the screen by mapping different colours to the screen in different
sequences.

Vector graphics use objects created from mathematical formulas to represent things like lines,
curves, fills, line thickness, etc. to create the image.

Each type of graphic has it's own advantages and disadvantages. Older versions of HTML were
only able to recognizes bitmapped graphics so most graphics created for the Internet, using
standard HTML, are created or converted to a bitmap format. The newest version of HTML or
XHTML is able to display vector graphics but not all browsers are able to display these graphics.

Within each of the two main types there are dozens of different formats. Graphics formats are
distinguished by their filename extensions.

Page | 9
The three main bitmapped format graphics used on the Internet are .gif, .jpeg (.jpg) and .png.
There are many others including .bmp, .tiff (.tif), .pcx, .ppm, .tga and a host of others.Some of
the structured formats are .ai, .cmx, .eps, .wpg, .cgm and a host of others.

Bitmapped graphics can be created and modified in a paint program and vector or structured
graphics can be created and modified in a draw program.

The main tools in a graphics program allow you to select a section of a picture, erase part of a
picture, fill a defined area, select a color, magnify a section, draw free hand, draw with various
tools such as a straight line; a curved line; a rectangle; an oval; and a polygon. You can also
modify a drawing by changing the size, color, placement, and, depending on the program,
hundreds of other modification.

1.1.1 Sound

Moving Picture Experts Group (MPEG) or .mpg is multimedia format that is an attempt to create
a standardization among the various formats available. MPEG has made it possible to place
audio content on your website without having it sound tiny and hollow or taking an extreme
amount of time to download. There are many different formats for sound including; Microsoft's
.wav, Sun's .au & .snd, Real Network’s RealAudio , .ra(*), and various others.

You may have heard .mid files play when visiting various websites. Musical Instruments Digital
Interface (MIDI) files are basically sound tracks which use a collection of sounds contained in
the .mid file to play a tune.

To create a sound file you will need an audio program. You can then record with a microphone
or off of a prerecorded medium. Your computer will need to have a sound card properly installed
and a speaker to hear your recording. You can save the sound file to play back later.

Page | 10
1.1.2 Animation

With the advent of faster computers comes animation. Though it has been around for years the
modern computer has made it possible to include animation in programs without causing them to
slow down (much). As with every multimedia format there are a number of types.

You may have seen .gif animations on this website. A GIF animation is a series of separate
images or frames that display one after the other to give the impression of movement. Other
formats are Audio Visual Interleaves’ avi, the before mentioned mpg, Microsoft's Media Player
.wmv, Apple's Quick Time .qt, .aif(*) & .mov, Real Network’s Real Video .rm(*), Macromedia's
Flash creates Shockwave .swf, and JavaScript as well as various others.

There are various animation or multimedia players available for a free download off the Internet.

To create animations, sounds or graphics you will need a program that has the capabilities you
want. Visit the various multimedia company websites to read up on their product to see if they
can do what you want. (Hint: to find a company website type "www.'replace this with the
companies name'.com"). Most companies offer free trials that you can download from their
website.

Page | 11
Experiment No. - 1
Objective:-To produce a single pixel and pre specified pattern on
screen: Theory:-
Color CRT Monitors:
A CRT monitor displays color pictures by using a combination of phosphors that emit different-
colored light. By combining the emitted light from the different phosphors, a range of colors can
be generated. The two basic techniques for producing color displays with a CRT are the beam-
penetration method and the shadow-mask method. The beam-penetration method for displaying
color pictures has been used with random-scan monitors. Two layers of phosphor, usually red
and green, are coated onto the inside of the CRT screen, and the displayed color depends on how
far the electron beam penetrates into the phosphor layers. A beam of slow electrons excites only
the outer red layer. A beam of very fast electrons penetrates through the red layer and excites the
inner green layer. At intermediate beam speeds, combinations of red and green light are emitted
to show two additional colors, orange and yellow. The speed of the electrons, and hence the
screen color at any point, is controlled by the beam-acceleration voltage. Beam penetration has
been an inexpensive way to produce color in random-scan monitors, but only four colors are
possible, and the quality of pictures is not as good as with other methods. Shadow-mask methods
are commonly used in raster scan systems (including color TV) because they produce a much
wider range of colors than the beam penetration method. A shadow-mask CRT has three
phosphor color dots at each pixel position. One phosphor dot emits a red light, another emits a
green light, and the third emits a blue light. This type of CRT has three electron guns, one for
each color dot, and a shadow-mask grid just behind the phosphor-coated screen. The delta delta
shadow-mask method, commonly used in color CRT systems. The three electron beams are
deflected and focused as a group onto the shadow mask, which contains a series of holes aligned
with the phosphor-dot patterns. When the three beams pass through a hole in the shadow mask,
they active e a dot triangle, which appears as a small color spot on the screen. The phosphor dots
in the triangles are arranged so that each electron beam can activate only its corresponding color

Page | 12
dot when it passes through the shadow mask. Another configuration for the three electron guns is
an in-line arrangement in which the three electron guns, and the corresponding red-green blue
color dots on the screen, are aligned along one scan line instead of in a triangular pattern. This
in-line arrangement of electron guns is easier to keep in alignment and is commonly used in
high-resolution color CRTs. We obtain color variations in a shadow-mask CRT by varying the
intensity levels of the three electron beams. By turning off the red and green guns, we get only
the color coming h m the blue phosphor. Other combinations of beam intensities produce a small
light spot for each pixel position, since our eyes tend to merge the three colors into one
composite. The color we see depends on the amount of excitation of the red, green, and blue
phosphors. A white (or gray) area is the result of activating all three dots with equal intensity.
Yellow is produced with the green and red dots only, magenta is produced with the blue and
red dots, and cyan shows up when blue and green are activated equally. In some low-cost
systems, the electron beam can only be set to on or off, limiting displays to eight colors.

Page | 13
Fig.: Shadow Mask Method
More sophisticated systems can set intermediate intensity levels for the electron beams, allowing
several million different colors to be generated. Color graphics systems can be designed to be
used with several types of CRT display devices. Some inexpensive home-computer systems and
video games are designed for use with a color TV set and an RF modulator. The purpose of the
RF modulator is to simulate the signal from a broadcast TV station. This means that the color
and intensity information of the picture must be combined and superimposed on the broadcast
carrier signal that the TV needs to have as input. As we might expect, this extra handling of the
picture information by the RF modulator and TV circuitry decreases the quality of displayed
images. Composite monitors are adaptations of TV sets that allow bypass of the broadcast
circuitry. These display devices still require that the picture information combined into a
composite signal and then separated by the monitor, so the resulting Video Display Devices
picture quality is still not the best attainable. Color CRTs in graphics systems are designed as
RGB monitors. These monitors use shadow-mask methods and take the intensity level for each
electron gun (red, green, and blue) directly from the computer system without any intermediate
processing. High-quality raster-graphics systems have 24 bits per pixel in the kame buffer,
allowing 256 voltage settings for each electron gun and nearly 17 million color choices for each
pixel. An RGB color system with 24 bits of storage per pixel is generally referred to as a full-
color system or a true-color system.

Source Code:-
#include<graphics.h>
#include<conio.h>

main()
{

Page | 14
int gd = DETECT, gm;

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

putpixel(25, 25, RED);

getch();
closegraph();
return 0;
}

Output:-

Page | 15
S. No. Viva Questions
1. What is Pixel?
2. What is Bitmap?
3. What is Refresh Buffer/Frame Buffer?
4. How many Bits used in Bitmap?
5. What is Pixmap?
6. How many Bits used in Pixmap?
7. The size of a 640*480 image at 240 pixels per inch is?
8. What is bit plane?
9. Mention the two Graphic software’s?
10. How many colors are possible with three bit plane frame buffer raster graphics
device?
11. Define digitizers?
12. What is Aspect ratio?
13. What is the Resolution ?.
14. What is aliasing?
15. What is the Anti aliasing?

Page | 16
Experiment No - 2

Objective:-To implement features like changing background color, fore ground color,
resizing window, repositioning of window

Theory:-
 Dot Pitch: It represents the distance which separates two phosphor dots of the same color.
The lower value of the dot pitch provide better image quality. A dot pitch equal to or less
than 0.25mm will be comfortable to use, while monitors with a dot pitch equal to or
greater than .28mm should be avoided.
 Persistence: It is one of the major differences between different phosphors. It is defined
as the time it takes the emitted light from the phosphor screen to decay to 10% of the
original light output. The decay is exponential.
 Refresh Rate: It represents the number of images which are displayed per second or in
other words number of times the image is reproduced each second. It is also called
vertical scan rate and is expressed in Hertz (Hz). Minimum refresh rate is 60 frames per
second.
 Resolution: The display resolution of a digital television or display device is the number
of distinct pixels in each dimension that can be displayed. It can be an ambiguous term
especially as the displayed resolution is controlled by all different factors in cathode ray
tube (CRT) and flat panel or projection displays using fixed picture-element (pixel)
arrays. The term “display resolution” is usually used to mean pixel dimensions, the
number of pixels in each dimension (e.g., 1920×1200), which does not tell anything
about the resolution of the display on which the image is actually formed: resolution
properly refers to the pixel density, the number of pixels per unit distance or area,
not total number of pixels.

Page | 17
 Definition: It is defined as the number of pixels that the screen can display. This number
is generally between 640x480 and 1600x1200, but higher resolutions are technically
possible.
 Size: It is calculated as measuring the diagonal of the screen. The screen’s definition is
different from size. A screen of given size can display different definitions.
 Aspect Ratio: The aspect ratio of an image is the ratio of the width of the image to its
height, expressed as two numbers separated by a colon. That is, for an x:yaspect ratio, no
matter how big or small the image is, if the width is divided into x units of equal length
and the height is measured using this same length unit, the height will be measured to
be y units. For example, consider a group of images, all with an aspect ratio of 16:9. One
image is 16 inches wide and 9 inches high. Another image is 16 centimeters wide and 9
centimeters high. A third is 8 yards wide and 4.5 yards high.

Aspect Ratio = (Yp/Ys)/(Xp/Xs)


Where, Yp is the total number of vertical points
Ys is maximum vertical height
Xp is the total number of horizontal points
Xs is maximum horizontal width.

Source Code:-
main()
{
int gd = DETECT, gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
midx = getmaxx()/2;
midy = getmaxy()/2;
setbkcolor(GREEN);

Page | 18
setviewport(midx - 50, midy - 50, midx + 50, midy + 50, 1);
circle(100,100,50); /* drawn in white color */
setcolor(RED);
circle(200,200,50); /* drawn in red color */

getch();
closegraph();
return 0;
}
Output:-

Page | 19
S. No. Viva Questions
1. What is Clipping?

2. What is the difference between Raster scan and Random scan?

3. How many bits are required for a 512 × 512 raster with each pixel being represented
by 3 bits?
4. Define point clipping.

5. In a raster system with resolution 2560 × 2048. How many pixels could be accessed
per second by a display controller that refresh the screen at a rate of 60 frames
per second. Also calculate access time per pixel in the system.
6. What is scan line algorithm?

7. How long would it take to load a 640 by 480 frame buffer with 12 bits per pixel, if
105 bits can be transferred per second?
8. Difference between Window port and View port?

9. If an image has a height of 2 inches and an aspect ratio of 1.5, what is its width?

10. What is meant by refreshing of the screen?

11. What are the types of Clipping?

12. What do you mean by ‘jaggier’?

13. What is the function of the control electrode in a CRT?

14. List out the merits and demerits of DVST?

15. Name the two methods by which an electron beam can be bent?

Page | 20
Experiment No - 3
Objective:-Write a program to implement Bresenham Line
algorithm. Theory:-

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.

Page | 21
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

Step11: Go to step 7

Step12: End of Algorithm

Source Code:-
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd = DETECT, gm;
int dx, dy, p, end;
float x1, x2, y1, y2, x, y;
initgraph(&gd, &gm, "c:\tc\bgi");
printf("Enter Value of X1: ");
scanf("%f", &x1);
printf("Enter Value of Y1: ");
scanf("%f", &y1);
printf("Enter Value of X2: ");

Page | 22
scanf("%f", &x2);
printf("Enter Value of Y2: ");
scanf("%f", &y2);
dx = abs(x1 - x2);
dy = abs(y1 - y2);
p = 2 * dy - dx;
if(x1 > x2)
{
x = x2;
y = y2;
end = x1;
}
else
{
x = x1;
y = y1;
end = x2;
}
putpixel(x, y, 10);
while(x < end)
{
x = x + 1;
if(p < 0)
{
p = p + 2 * dy;
}
else

Page | 23
{
y = y + 1;
p = p + 2 * (dy - dx);
}
putpixel(x, y, 10);
}
getch();
closegraph();
}

Output:-

Page | 24
S. No. Viva Questions
1. What are the Advantages of Bresenhem's Algorithm?
2. What do you call the path the electron beam takes when returning to the left side of
the CRT screen?
3. What is the refresh rate of Flicker?
4. Write short notes on active and passive transformations?

5. What do you call the path the electron beam takes at the end of each refresh cycle?

6. List out the various Text clipping?

7. List out the merits and demerits of Penetration techniques.

8. What is fixed point scaling?

9. What is covering (exterior clipping)?

10. What is the pitch of a color CRT?

11. Explain the working principle of CRT?

12. Explain about the various application of Computer Graphics?

13. What are the various attributes of a line?

14. What is the access rate/pixel of a 4096 × 4096 raster having a refresh rate of 30
frames/sec?
15. What is Transformation?

Page | 25
Experiment No - 4
Objective:- Write a program to implement DDA Line algorithm.

Theory:-

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

Page | 26
Advantage:
1. It is a faster method than method of using direct use of line equation.
2. This method does not use multiplication theorem.
3. It allows us to detect the change in the value of x and y ,so plotting of same point
twice is not possible.
4. This method gives overflow indication when a point is repositioned.
5. It is an easy method because each step involves just two additions.

Disadvantage:
1. It involves floating point additions rounding off is done. Accumulations of round
off error cause accumulation of error.
2. Rounding off operations and floating point operations consumes a lot of time.
3. It is more suitable for generating line using the software. But it is less suited for
hardware implementation.

Source Code:-
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<ctype.h>
#include<math.h>
#include<stdlib.h>
void draw(int x1,int y1,int x2,int y2);
void main()
{
int x1,y1,x2,y2;
int gdriver=DETECT,gmode,gerror; initgraph(&gdriver,&gmode,”c:\\tc\\
bgi:”);

Page | 27
printf(“\n Enter the x and y value for starting point:\n”);
scanf(“%d%d”,&x1,&y1);
printf(“\n Enter the x and y value for ending point:\n”);
scanf(“%d%d”,&x2,&y2);
printf(“\n The Line is shown below: \n”);
draw(x1,y1,x2,y2);
getch();
}
void draw(int x1,int y1,int x2,int y2)
{
float x,y,xinc,yinc,dx,dy;
int k;
int step;
dx=x2-x1;
dy=y2-y1;
if(abs(dx)>abs(dy))
step=abs(dx);
else
step=abs(dy);
xinc=dx/step;
yinc=dy/step;
x=x1;
y=y1;
putpixel(x,y,1);
for(k=1;k<=step;k++)
{
x=x+xinc;

Page | 28
y=y+yinc;
putpixel(x,y,2);
}
}

Page | 29
S. No. Viva Questions
1. What is DDA?

2. What is run length encoding?

3. What is the need of homogeneous coordinates?

4. What are the disadvantages of DDA algorithm?

5. What is Translation?

6. Given the portrait image of a person, describe a simple way to make the person look
more slender.
7. Explain Cohen Sutherland Line Clippings Algorithm?

8. What is dpi?

9. Define coherence properties.

10. What is Depth Buffer / Z-Buffering Method?

11. What is Computer Graphics?

12. What is point in the computer graphics system?

13. What is Color Look up table?

14. What is the advantage of introducing the matrix form of translation?

15. What is Scan conversion?

Page | 30
Experiment No -5
Objective:-Write a program to implement midpoint circle
algorithm. Theory:-
Step1: Put x =0, y =r

We have p=1-r

Step2: Repeat steps while x ≤ y


Plot (x, y)
If (p<0)
Then set p = p + 2x +
3 Else
p = p + 2(x-y)+5
y =y - 1 (end if)
x =x+1 (end loop)

Step3: End

Source Code:-
#include<stdio.h>
#include<conio.h>
#include<graphics.h>

void main()
{
int gd=DETECT,gm;
int x,y,r;
void Drawcircle(int,int,int);
printf("Enter the Mid points and Radious:");
scanf("%d%d%d",&x,&y,&r);
initgraph(&gd,&gm,"");

Page | 31
Drawcircle(x,y,r);
getch();
closegraph();
}

void Drawcircle(int x1,int y1,int r)


{
int x=0,y=r,p=1-r;
void cliplot(int,int,int,int);
cliplot(x1,y1,x,y);
while(x<y)
{ x+
+;
if(p<0)
p+=2*x+1;
else
{
y--;
p+=2*(x-y)+1;
}
cliplot(x1,y1,x,y);
}
}
void cliplot(int xctr,int yctr,int x,int y)
{
putpixel(xctr +x,yctr +y,1);
putpixel(xctr -x,yctr +y,1);

Page | 32
putpixel(xctr +x,yctr -y,1);
putpixel(xctr -x,yctr -y,1);
putpixel(xctr +y,yctr +x,1);
putpixel(xctr -y,yctr +x,1);
putpixel(xctr +y,yctr -x,1);
putpixel(xctr -y,yctr -x,1);
getch();
}

Page | 33
S. No. Viva Questions
1. Define Circle?

2. How many memory bits are required for a 24-bit plane 1024 × 1024 element raster?

3. What is the Rotation?

4. Distinguish between uniform scaling and differential scaling?

5. What is Back face removal?

6. What is Ray Tracing?

7. What are the limitations of Back Face removal algorithm?

8. What is use of a buffer method?

9. What is Back Face Detection method?

10. Define Computer Animation?

11. What is Visible-Surface Detection?

12. What are the steps in animation sequence?

13. What is Object-Space method?

14. What is Image-space method?


15. What is Depth-Sort Method?

Page | 34
Experiment No - 6
Objective:-Write a program to fill an ellipse.
Source Code:-
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy, i;
int xradius = 100, yradius = 50;

/* initialize graphics and local variables */


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

/* read result of initialization */


errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

Page | 35
midx = getmaxx() / 2;
midy = getmaxy() / 2;

/* loop through the fill patterns */


for (i = EMPTY_FILL; i < USER_FILL; i++) {
/* set fill pattern */
setfillstyle(i, COLORS(12));

/* draw a filled ellipse */


fillellipse(midx, midy, xradius,
yradius); getch();
}

/* clean up */
closegraph();
return 0;
}

Page | 36
S. No. Viva Questions
1. What is Mid Point Ellipse Algorithms?

2. Define Ellipse?

3. What is Boundary Fill Algorithm?

4. What is Flood Fill/ Seed Fill Algorithm?

5. Difference between Boundary Fill & Flood Fill Algorithm?

6. Which are the two techniques use in Boundary Fill Algorithm?

7. What are the advantages of rendering polygons by scan line method?

8. What are the advantages of rendering by patch splitting?

9. What is space partitioning representation of polygon?

10. Explain the classification of light sources.

11. Define ray casting?

12. What is boundary representation of polygon?

13. Define polygon.

14. Explain the sweep representation.


15. Distinguish between convex and concave polygons.

Page | 37
Experiment No - 7
Objective:- Write a program to fill a
polygon. Theory:-

Flood –Fill Algorithm:


The flood fill algorithm takes three parameters: a start node, a target color, and a replacement
color. The algorithm looks for all nodes in the array which are connected to the start node by a
path of the target color, and changes them to the replacement color. There are many ways in
which the flood-fill algorithm can be structured, but they all make use of a queue or stack data
structure, explicitly or implicitly. One implicitly stack-based (recursive) flood-fill
implementation (for a two-dimensional array) goes as follows:

Flood-fill (node, target-color, replacement-color):


1. If the color of node is not equal to target-color, return.
2. Set the color of node to replacement-color.
3. Perform Flood-fill (one step to the west of node, target-color, replacement-
color). Perform Flood-fill (one step to the east of node, target-color,
replacement-color). Perform Flood-fill (one step to the north of node, target-
color, replacement-color). Perform Flood-fill (one step to the south of node,
target-color, replacement-color).
4. Return.

Page | 38
Source Code:-
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int i, x, y;
int corner[8];
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
x = getmaxx()/4;
y = getmaxy()/4;

corner[0] = x;
corner[1] = y;

Page | 39
corner[2] = x+200;
corner[3] = y+0;

corner[4] = x+200;
corner[5] = y+150;
corner[6] = x+0;
corner[7] = y+150;
for (i=EMPTY_FILL; i<USER_FILL; i++)
{
setfillstyle(i, COLORS(random(15)));
fillpoly(4, corner);
getch();
}
closegraph();
return 0;
}

Page | 40
S. No. Viva Questions
1. Explain diffuse reflection.

2. Explain the Cyrus Beck Line Clipping Algorithm?

3. Explain Specular Reflection.

4. Define reflection. What are the laws of reflection?.

5. Define forward and backward rendering.

6. Explain the illumination model.

7. What is a spline?

8. Define B-Spline curve?

9. What are the different ways of specifying spline curve?

10. What are the important properties of Bezier Curve?

11. Define Color model?

12. What is chromaticity?

13. What is HSV model?

14. What for CMY color model used?


15. What are the parameters in the HLS color model?

Page | 41
Experiment No - 8
Objective:- Write a program to hoist a
flag. Theory:-

2D Transformations

Translation

This transformation moves points of an object to a new specified position. Translation is defined
by a vector of the shift p = (X1-X2, Y1-Y2), where (X1, Y1) are coordinates of the object in its
first position and (X2, Y2) are its coordinates in the second position.

Translation matrix is :

| 1 0 0|
A=| 0 1 0|
| tx ty 0 |

Rotation

Page | 42
Rotation can be described as circular motion about some axis, in this case the axis is one of the
object's local axes. Transformation of an object around a static point on a circular trajectory is
called rotation. It is defined by a rotation angle and rotation centre.

After a rotation of point P[x, y] around the centre of co-ordinates system O=[0, 0] by angle alfa
we will get a new point P' with coordinates

x'= x*cos(alfa) - y*sin(alfa) y'= x*sin(alfa) + y*cos(alfa)

Matrix transformation for rotation is

| cos(alfa) sin(alfa) 0 |
Ao = |-sin(alfa) cos(alfa) 0 |
| 0 0 1|

Scaling

A change of scale also causes a change of object's size in the directions of the coordinates axes.
If the coefficient of proportion of the new length to the old one is higher than 1 in a direction of

Page | 43
one of the axes then the object will be prolonged, if the coefficient is lower than 1, then the
object will be shortened.

The formule for the change of scale for the point P [x, y] is

x'=Sx*x
y' = Sy * y

The scaling equations are represented in matrix form as

| Sx 0 0 |
As = | 0 Sy 0 |
| 0 0 1|

Composition of 2D transformations

When composing transformations, it is important not to change the right order of


transformations. A transformations originated by composing of other ones, can be expressed by
one matrix by gradual multiplication of matrix representing original partial transformations.

Source Code:-
#include <dos.h>

Page | 44
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
int gdriver = DETECT, gmode,poly[10],poly1[10],poly2[10],poly3[10];
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
//pole
{
poly[0]=50;
poly[1]=50;

poly[2]=60;
poly[3]=50;

poly[4]=60;
poly[5]=400;

poly[6]=50;
poly[7]=400;

poly[8]=50;
poly[9]=50;

setfillstyle(SOLID_FILL,WHITE);

Page | 45
fillpoly(4,poly);
}
// flag
{
poly1[0]=60;
poly1[1]=50;

poly1[2]=320;
poly1[3]=50;

poly1[4]=320;
poly1[5]=100;

poly1[6]=60;
poly1[7]=100;

poly1[8]=60;
poly1[9]=50;

setfillstyle(SOLID_FILL,RED);
fillpoly(4,poly1);
}
{
poly2[0]=60;
poly2[1]=100;

poly2[2]=320;

Page | 46
poly2[3]=100;

poly2[4]=320;
poly2[5]=150;

poly2[6]=60;
poly2[7]=150;

poly2[8]=60;
poly2[9]=100;

setfillstyle(SOLID_FILL,WHITE);
fillpoly(4,poly2);

}
{
poly3[0]=60;
poly3[1]=50;

poly3[2]=320;
poly3[3]=50;

poly3[4]=320;
poly3[5]=200;

poly3[6]=60;
poly3[7]=200;

Page | 47
poly3[8]=60;
poly3[9]=50;

setfillstyle(SOLID_FILL,RED);
fillpoly(4,poly3);
}
{
setfillstyle(SOLID_FILL,BLINK);
pieslice(190,126 ,0,45,25);
pieslice(190,126 ,45,90,25);
pieslice(190,126 ,90,135,25);
pieslice(190,126 ,135,180,25);

pieslice(190,126 ,180,225,25);
pieslice(190,126 ,225,270,25);
pieslice(190,126 ,270,315,25);
pieslice(190,126 ,315,360,25);
}

getch();
closegraph();
return 0;
}

Page | 48
Output:-

Page | 49
S. No. Viva Questions
1. What are the design issues for multimedia authoring?

2. What is panning?

3. Define mail message.

4. What are the components of a distributed Multimedia system?

5. What are the primary n/w topologies used for multimedia?

6. Give the primary goal of MAPI.

7. What is the purpose of MIME?

8. What are the characteristics of image and still video stores ?

9. Can you tell which major components (hardware and software) are needed for
computer graphics?
10. Define Multimedia.

11. List out the building blocks of multimedia.

12. What are the types of sound objects that can be used in multimedia production?

13. Define the following terms: (i) Compression Ratio (ii) Image Quality

14. What are the basic tools that are required for the multimedia Software?

15. List the challenges in multimedia.

Page | 50
Experiment No - 9
Objective: - Write a program to create balloons.

Source Code:-
#include <dos.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
while(!kbhit())
{
int i,j=0;
for(i=440,j=0;i>20,j<400;i--,j++)
{
int k=180+j;
setfillstyle (SOLID_FILL,WHITE);
fillellipse(k,i,50,90);
fillellipse(k,i+95,5,10);
line(k+5,i+100,k-20,i+270);
setfillstyle (SOLID_FILL,RED);
fillellipse(180,i,50,90);
fillellipse(180,i+95,5,10);

Page | 51
line(185,i+100,220,i+300);
setfillstyle (SOLID_FILL,BLUE);
fillellipse(250,i,50,90);
fillellipse(250,i+95,5,10);
line(250,i+100,220,i+300);
setfillstyle (SOLID_FILL,GREEN);
fillellipse(310,i,50,90);
fillellipse(310,i+95,5,10);
line(310,i+100,220,i+300);
setfillstyle (SOLID_FILL,MAGENTA);
fillellipse(210,i+60,50,90);
fillellipse(210,i+155,5,10);
line(210,i+160,220,i+300);
setfillstyle (SOLID_FILL,YELLOW);
fillellipse(270,i+60,50,90);
fillellipse(270,i+155,5,10);
line(270,i+160,220,i+300);
delay(50);
cleardevice();
}
}
getch();
closegraph();
return 0;
}

Page | 52
Output:-

S. No. Viva Questions


1. List different color models.
2. Different between database and multimedia database.
3. List out the input devices of multimedia.
4. What is the use of control points?

5. Define Projection.

6. Different between database and multimedia database.


7. What are the minimum requirements needed for running multimedia application?
8. What RTP?
9. What is audio streaming?
10. What are the design issues for multimedia authoring?
11. What is the purpose of zooming?
12. What is projection?
13. What are the types of projection?
14. What is Perspective projection?
15. What is parallel projection?

Page | 53
Experiment No -10
Objective:-Write a program to implement a walking robot.
Theory:-

Perspective projection:-

When the human eye looks at a scene, objects in the distance appear smaller than objects close
by - this is known as perspective. While orthographic projection ignores this affect to allow
accurate measurements, perspective definition shows distant objects as smaller to provide
additional realism.

The perspective projection requires greater definition. A conceptual aid to understanding the
mechanics of this projection involves treating the 2D projection as being viewed through a
camera viewfinder. The camera's position, orientation, and field of view control the behavior of
the projection transformation. The following variables are defined to describe this
transformation:

 - the point in 3D space that is to be projected.


 - the location of the camera.

 - The rotation of the camera. When and


the 3D vector <1,2,0> is projected to the 2D vector <1,2>.
 - the viewer's position relative to the display surface.

Which results in:

 - the 2D projection of .

First, we define a point as a translation of point into a coordinate system defined by .


This is achieved by subtracting from and then applying a vector rotation matrix using to

Page | 54
the result. This transformation is often called a camera transform, and can be expressed as
follows, expressing the rotation in terms of rotations about the x, y, and z axes (these calculations
assume that the axes are ordered as a left-handed system of axes): [2] [3]

This representation correspond to rotating by three Euler angles (more properly, Tait–Bryan
angles), using the xyz convention, which can be interpreted either as "rotate about the extrinsic
axes (axes of the scene) in the order z, y, x (reading right-to-left)" or "rotate about the intrinsic
axes (axes of the camera) in the order x, y, z) (reading left-to-right)". Note that if the camera is

not rotated ( ), then the matrices drop out (as identities), and this reduces to
simply a shift:

Alternatively, without using matrices, (note that the signs of angles are inconsistent with matrix
form):

This transformed point can then be projected onto the 2D plane using the formula (here, x/y is
used as the projection plane, literature also may use x/z):

Or, in matrix form using homogeneous coordinates, the system

Page | 55
in conjunction with an argument using similar triangles, leads to division by the homogeneous
coordinate, giving

The distance of the viewer from the display surface, , directly relates to the field of view,

where is the viewed angle. (Note: This assumes that you map the points
(-1,-1) and (1,1) to the corners of your viewing surface)

Subsequent clipping and scaling operations may be necessary to map the 2D plane onto any
particular display media.

Source Code:-
#include<dos.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");

Page | 56
errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

int i,x,y,poly[10];
{
while(!kbhit() && (x=620))
{
for(x=0;x<=620;x=x+10)
{
/*f*/

setfillstyle(SOLID_FILL,COLORS(6));
fillellipse(x+50,150,25,25);
setfillstyle(SOLID_FILL,COLORS(BLACK));
fillellipse(x+65,145,3,3);

/*c*/
poly[0]=x+25;
poly[1]=175;

poly[2]=x+75;

Page | 57
poly[3]=175;

poly[4]=x+75;
poly[5]=300;

poly[6]=x+25;
poly[7]=300;

poly[8]=x+25;
poly[9]=175;

drawpoly(5,poly);
/*h1*/
line(x+50,200,x+20,315);
line(x+52,202,x+20,320);
/*h2*/
line(x+75,230,x+90,280);
line(x+75,232,x+94,285);
/*l1*/
line(x+50,300,x+100,430);
line(x+57,300,x+107,430);
/*l2*/
line(x+46,300,x+25,430);
line(x+53,300,x+32,430);

/*p1*/
line(x+23,430,x+55,430);

Page | 58
line(x+23,435,x+55,435);
/*p2*/

line(x+97,430,x+129,430);
line(x+97,435,x+129,435);

delay(150);
cleardevice();
}

}
}
getch();
closegraph();
return 0;
}

Page | 59
S. No. Viva Questions

1. What is JPEG?

2. Assuming that a certain full-color (24 bit per pixel) RGB raster system has a 512 by
512 frame buffer, how many distinct color choices (intensity levels) would be
available?
3. What is the difference between impact and non-impact printers?

4. What is projector?

5. What is hypermedia documents?

6. What are types of moving picture?

7. What is digital pen?

8. Can you give some basic features of computer graphics?

9. What is tiling patterns?

10. What is soft fill?

11. How many colors are possible with three bit plane frame buffer raster graphic
device?
12. Interpolating curve always pass through what control point?

13. Approximating curve always pass through what control points ?

14. What is cell array?

15. What is morphing?

Page | 60
Experiment No - 11
Objective: - Write a program to implement a rotating

wheel. Rotation:-

Rotation of an object in space is done by means of rotation around coordinate axes.

Transformation matrix of rotation about the x axis by angle u :

|1 0 0 0|
| 0 cos u sin u 0 |
Ax = | 0 -sin u cos u 0 |
|0 0 0 1|

Transformation matrix of rotation about the y axis by angle u :

| cos u 0 sin u 0 |
| 0 1 0 0|
Ay = | -sin u 0 cos u 0 |
| 0 0 0 1|

Transformation matrix of rotation about the z axis by angle u :


| cos u sin u 0 0 |

|-sin u cos u 0 0 |
Az =| 0 0 1 0|
| 0 0 0 1|

Example of rotation:

Let's take point (X, Y, Z) to rotate about the point (0, 0, 0)

Page | 61
1. The 2D rotation about the x axis by angle u

X' = X
Y' = Y * cos(u) - Z * sin(u)
Z' = Y * sin(u) + Z *cos(u)

2. rotate about the y axis by angle u

X' = X * cos(u) + Z * sin(u)


Y' = Y
Z' = Z *cos(u) - X * sin(u)

3. rotate about the z axis by angle u

X' = X * cos(u) - Y * sin(u)


Y' = Y *cos(u)+-X * sin(u)
Z' = Z

Finally, result coordinate of point are (X', Y', Z').

Scaling:-

Scale change - scaling in space is represented by the following transformation matrix:

| Sx 1 0 0 |
| 1 Sy 0 0 |
As = | 0 0 Sz 0 | ,
| 0 0 01|

where coefficients Sx, Sy and Sz determine scale point of the coordinate axis.

Page | 62
Example : Vector (x, y, z, 1) is to be magnified to (x*Sx, y*Sy, z*Sz, 1)

The vector will be multiplied by the transformation matrix :

| sx 0 0 0 |
| x y z 1 | * | 0 sy 0 0 | = |x*sx y*sy z*sz 1|
| 0 0 sz 0 |
|0001|

Symetry

Like in surface, in space symetry is a special case of scale change, where values of Sx, Sy and Sz
are either 1 or -1.

Sx Sy Sz
symetry by x axis <1 -1 -1
symetry by y axis -1 1 -1
symetry by z axis -1 -1 1
symetry by xy plane 1 1 -1
symetry by plane xy 1 -1 1
symetry by plane xy -1 1 1
symetry by center -1 -1 -1

Shear transformations

In space, we divide shear transformation according to the direction of the surfaces xy,xz and yz.
Values of Sx,Sy and Sz determine shear transformation sizes for all the directions.

Page | 63
A shear transformation about the xy plane

| 1 000|
| 0 100|
Axy = | Sx Sy 0 0 |.
| 0 001|

A shear matrix about the xz plane

| 1 0 0 0|
| Sx 1 Sz 0 |
Axz = | 0 1 1 0 |.
| 0 0 0 1|

A shear matrix about the yz plane

| 1 Sy Sz 0 |
|0 1 00|
Ayz = | 0 0 1 0 |.
|0 0 01|

Source Code:-
#include<graphics.h>
#include<dos.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int gdriver = DETECT, gmode, errorcode;

Page | 64
int i,x,y;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi”);
errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
int j;
x=0;
y=getmaxy()/2;
while (!kbhit() && (x=640))
{
for(x=0;x<=620;x=x+15)
{
circle(x,y,100);
{
circle(x,y,90);
pieslice(x,y,0, 90, 90);
pieslice(x,y,90,180, 90);
pieslice(x,y,180,270, 90);
pieslice(x,y,270,360, 90);
delay(150);
circle(x,y,5);
cleardevice();

Page | 65
}
circle(x,y,100);
circle(x,y,90);
pieslice(x,y,0, 45, 90);
pieslice(x,y,90,135, 90);
pieslice(x,y,180,225, 90);
pieslice(x,y,270,315, 90);
setfillstyle(EMPTY_FILL,getmaxcolor());
circle(x,y,5);
delay(150);
cleardevice();
}}
closegraph();
exit(1);}

Page | 66
Experiment No - 12
Objective:-Write a program to implement Cohen Sutherland

algorithm. Theory:-

Clipping-:

When displaying an object on the display box it can happen that a part of the displayed does not
fit in the display box, it lies outside the display box. So, in the course of displaying we are
clipping this part. Now, we will be interested in clipping the elements: a point, an abscissa, a
text, a polygon. Clipping is in fact a special case of the conjunction of two objects: the display
box and the graphics elements.

Clipping a point in a window

Clipping looks trivial in the case of a dot, we just have to add a few comparisons checking if the
coordinates are in the display box range and proceed only if that is the case:

The question is whether a point B with coordinates (mx, my) belongs to the display box or not.
Let us take a display box given by coordinates of the lower left corner xmin, ymin and the right
upper corner xmax, ymax. The question is whether a point B with coordinates (mx, my) belongs
to the display box or not.

The answer is: If it is valid that xmin =< mx =< xmax and ymin =< my =< ymax , then the point
belongs in the display box.

A simple algorithm on testing whether the given point [mx, my] is in the display box [x1, y1],
[x2, y2]:
And of course if we are always clipping to a rectangular with a diagonal (0, 0-something_x,

Page | 67
something_y) we can do it with just 2 comparisons instead of 4, just making sure x and y passed
are considered by unsigned comparisons, (negative numbers after all would be thought of just
very large positive numbers).

if ((mx>=x1)&&(mx=<x2)&&(my>=y1)&&(my=<y2))
{
// point is in window
}
else
{
// point is out of the window
}

Cohen-Sutherland clipping algorithm

The first part of this algorithm serves simply for excluding abscissas at which it isn't necessary
to calculate the conjunction with the display box. Firstly, we split a plane into 9 sections, while
the middle section represents a display box. For every section is allocated a 4-bit code, and such
code is allocated also to the point of abscissa which belongs into this section. Individual bits for a
point [x, y] are set as follows:

1. bit - a point lying left of the display box ( xmin > x )


2. bit - a point lying right of the display box ( xmax < x )
3. bit - a point lying lower than the display box ( ymin > y )
4. bit - a point lying higher than the display box ( ymax < y )

Page | 68
A point located inside the display box has the code 0000. The abscissa is lying wholly inside
in the display box. We can exclude this abscissa if both its points are left, right, above or down
from the display box. We can easily identify this just by the codes of the end points. We take
both codes of the end points of an abscissa, and we make their logical conjunction ((1 and 1) = 1,
otherwise 0). If it is different from 0000, then the abscissa doesn't intersect the display box, and
we can exclude it. In the opposite case, we cannot exclude this abscissa, and we must test it for a
conjunction in respect of the display box limits, 4 times in a worst case.

Page | 69
Source Code:-
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<math.h>

typedef unsigned char BYTE; // 0 to 255 or 0 to 1111-1111 ie 0xff


BYTE pointcheck(int x, int y);
BYTE bit1check(int p);
BYTE bit2check(int p);
BYTE bit3check(int p);
BYTE bit4check(int p);
int endprog(void);
int main(void)
{
//graphics mode initialzation to 640x480 resolution
int gd=VGA,gm=VGAHI;
initgraph(&gd,&gm,"");
//window defined
float x,y,xmin,ymin,xmax,ymax;
xmax=540,ymax=380,xmin=100;ymin=100;
//line end points defined
float xn1,xn2,yn1,yn2,x1,y1,x2,y2;
int p1,p2;
x1=120;y1=12;x2=300;y2=390; // with less values of point 1
//draw initial situtation
setcolor(1);

Page | 70
rectangle(xmin,ymin,xmax,ymax);
setcolor(2);
line(x1,y1,x2,y2);
//program of clipping begins here
//bits are numbered as 1 1 1 1
// ^fourth ^third ^second ^first
float m=(y2-y1)/(x2-x1); //slope calculated
//getting binary conversion of points
p1=pointcheck(x1,y1);
p2=pointcheck(x2,y2);
//printing line position
int bit1,bit2,bit3,bit4;
bit1=bit1check(p1);
bit2=bit2check(p1);
bit3=bit3check(p1);
bit4=bit4check(p1);
printf("point p1 is %d =%d%d%d%d",p1,bit4,bit3,bit2,bit1);
bit1=bit1check(p2);
bit2=bit2check(p2);
bit3=bit3check(p2);
bit4=bit4check(p2);
printf("\n point p2 is %d=%d%d%d%d",p2,bit4,bit3,bit2,bit1);
//if the line lies outside exit program
if (bit1check(p1)&bit1check(p2)==1)endprog();
if (bit2check(p1)&bit2check(p2)==1)endprog();
if (bit3check(p1)&bit3check(p2)==1)endprog();
if
(bit4check(p1)&bit4check(p2)==1)endprog();

Page | 71
if (p1==0 & p2==0)
{
printf("\n line lies within the window");
getch();
return 0;
}
else printf("\n clipping....");
//clipping required from interesting points .calculating that..
int pointcount=0;
if(pointcheck(x1,y1)==0) //if it starts from within window
{
xn1 = x1;yn1 = y1;
pointcount =pointcount +1;
p1=p2;
}
if(bit1check(p1)==1) //it crosses xmin
{
x=xmin;
y=y1+m*(xmin-x1);
putpixel(x,y,3);
setcolor(3);
circle(x,y,4);
if(pointcount>0)
{
xn2=x;yn2=y;
}
else {

Page | 72
xn1=x;yn1=y;
pointcount=pointcount+1;
}
p1=p2;
}
if(bit2check(p1)==1)//it crosses xmax
{
x=xmax;
y=y1+m*(xmax-x1);
putpixel(x,y,3);
setcolor(3);
circle(x,y,4);
if(pointcount>0)
{
xn2=x;yn2=y;
}
else {
xn1=x;yn1=y;
pointcount=pointcount+1;
}
p1=p2;
}
if(bit3check(p1)==1) //it crosses ymin
{
y=ymin; x=x1+
(ymin-y1)/m;
putpixel(x,y,3);

Page | 73
setcolor(3);
circle(x,y,4);
if (pointcount >0)
{
xn2=x;yn2=y;
}
else {
xn1=x;yn1=y;
pointcount=pointcount+1;
}
p1=p2;
}
if(bit4check(p1)==1) //it crosses ymax
{
y=ymax; x=x1+
(ymax-y1)/m;
putpixel(x,y,3);
setcolor(3);
circle(x,y,4);
if (pointcount>0)
{
xn2=x; yn2=y;
}
else {
xn1=x; yn1=y;
pointcount=pointcount+1;
}

Page | 74
}
getch();
setcolor(0);
line(x1,y1,x2,y2);
setcolor(4);
line(xn1,yn1,xn2,yn2);
getch();
closegraph();
}
int endprog(void)
{
printf("\n line lies outside the window");
getch();
closegraph();
return 0;
}
//function returns binary value of point location
BYTE pointcheck(int x,int y)
{
//xmax=540;ymax=380;xmin=100;ymin=100;
int val=0x00;
if((x-100)<0) val=val|0x01;//make bit 1-->1
if((540-x)<0) val=val|0x02; //make bit 2 -->1
if((y-100)<0) val=val|0x04; //make bit 3 -->1
if((380-y)<0) val=val|0x08; //make bit 4 -->1
return val;
}

Page | 75
//subroutines for checking individual bit values
BYTE bit1check(int a)
{
a=a&1; //and operation with 0001,making 2,3,4 bit0
return a;
}
BYTE bit2check(int b)
{
b=b&2;//and with 0010 i.e making 1,3,4,bit 0
b=b>>1; //right shift by 1 bit i.e cutting last digit
return b;
}
BYTE bit3check(int c)
{
c=c&4; //and with 0100 i.e making 1,2,4 bit 0
c=c>>2; //right shift 2 digits i.e cutting last two digit
return c;
}
BYTE bit4check(int d)
{
d=d>>3; //right shift 3 digits i.e cutting last three digit
return d;
}

Page | 76

You might also like