0% found this document useful (0 votes)
36 views113 pages

CGR Allunits Notes Ankushhh

Uploaded by

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

CGR Allunits Notes Ankushhh

Uploaded by

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

UNIT 1: BASICS OF COMPUTER GRAPHICS

CO1 : Manipulate visual and geometric information of images

Pixel:
A pixel (short for picture element, using the common abbreviation "pix" for
"picture") is one of the many tiny dots that make up the representation of a
picture in a computer's memory.
The intensity of each pixel is variable; in color systems, each pixel has
typically three or four dimensions of variability such as red, green and blue,
or cyan, magenta, yellow and black.

Resolution
• Resolution is the number of rows that appear from top to bottom of a screen
and in turn the number of pixels or pixel elements that appear from left to
right on each scanline.

• Based on this resolution only the effect of picture appears on screen.

1) Image Resolution: It refers to pixel spacing. In normal PC monitor it


ranges between 25 to 80 pixels perinch.

2) Screen Resolution: It is thenumber of distinctpixels in each dimension that


can be displayed.

1
UNIT 1: BASICS OF COMPUTER GRAPHICS
Text mode

• Text mode is a personal computer display setting that divides the display
screen into 25 rows and 80 columns in order to display text without images.

• In text mode, each box can contain one character. Text mode is also known as
character mode or alphanumeric mode. In character mode, the display screen
is treated as an array of blocks, each of which can hold one ASCII character.

Graphics Mode

Graphics mode is the more sophisticated. Programs that run in graphics


mode can display an unlimited variety of shapes and fonts.
Programs that run entirely in graphics mode are called graphics- based
programs. In graphics mode, the display screen is treated as an array of
pixels. Characters and other shapes are formed by turning on combinations
of pixels.

Graphics Mode Graphics Function

The graphics-mode functions allow you to draw dots, lines, and shapes (like
circles, rectangles, and ellipse etc.), add color to lines and areas, and perform
many other graphics-related activities.

Setting up Graphics Mode

detectgraph() : This function checks the system and returns two integer
parameters: a value representing the system's graphics driver and a value for the
recommended graphics mode if an adapter is installed.
The mode value is the highest resolution possible with that adapter. Syntax:
detectgraph(int *gdriver, int *gmode); initgraph (): This library function must be
executed before any other graphics mode functions can be used.
This requires the GRAPHICS.Hheaderfile. Syntax: initgraph(int*driver, int
*mode, char *path); where *driver is the graphics driver,
given by an integer.
*mode is the graphics mode, given by an integer.

2
UNIT 1: BASICS OF COMPUTER GRAPHICS
*path is a string indicating where the driver is available note:The Driver
is a file extention BGI.Each type of hardware requires a different driver.A
null string ("") indicates sriver is in the current directory.

Graphics Pipeline

• A graphics pipeline can be divided into three main parts: Application, Geometry
and Rasterization.

The application step is executed by the software on the main processor (CPU), it cannot
be divided into individual steps, which are executed in a pipelined manner. However, it
is possible to parallelize it on multi-core processors or multi-processor systems. In the
application step, changes are made to the scene as required, for example, by user
interaction by means of input devices or during an animation. The new scene with all
its primitives, usually triangles, lines and points, is then passed on to the next step in
the pipeline.

The geometry step (with Geometry pipeline), which is responsible for the majority of
the operations with polygons and their vertices (with Vertex pipeline), can be divided
into the following five tasks. It depends on the particular implementation of how these
tasks are organized as actual parallel pipeline steps.

3
UNIT 1: BASICS OF COMPUTER GRAPHICS

The Rasterization step is the task of taking an image described in a vector graphics
format (shapes) and converting it into a raster image (pixels or dots) for output on a
video display or printer, or for storage in a bitmap file format. It refers to both
rasterization of models and 2D rendering primitives such as polygons, line segments,
etc.

Bitmap based Graphics

Bitmap (or raster) images are stored as a series of tiny dots called pixels. Each pixel
is actually a very small square that is assigned a color, and then arranged in a pattern
to form the image. When you zoom in on a bitmap image you can see the individual
pixels that make up that image. The three most popular image formats used on the
Web (PNG, JPEG, and GIF) are bitmap formats. The bitmap format is excellent for
creating backgrounds and overlay elements.

Vector based graphics

Vector images are not based on pixel patterns, but instead use mathematical formulas
to draw lines and curves that can be combined to create an image from geometric
objects such as circles and polygons. All major browsers support the SVG (Scalable
Vector Graphics) format. Vector graphics are more flexible than bit- maps because
they can be easily re-sized. Vector-based graphics can be very useful when creating
large illustrations, as these graphics are resolution independent.

Applications of Computer Graphics

• Computer graphics user interfaces (GUIs) − A graphic, mouse-oriented


paradigm which allows theuser to interact with a computer.
• Businesspresentationgraphics −"Apictureis worthathousandwords".

4
UNIT 1: BASICS OF COMPUTER GRAPHICS
• Cartography − Drawing maps.
• Weather Maps −Real-timemapping, symbolic representations.
• Satellite Imaging − Geodesic images.
• Photo Enhancement − Sharpening blurred photos.
• Medical imaging − MRIs, CAT scans, etc. - Non-invasive internal
examination.
• Engineering drawings − mechanical, electrical, civil, etc. - Replacing the
blueprints of thepast.
• Architecture − Construction plans, exterior sketches - replacing the blueprints
and hand drawings of the past.
• Art − Computers provide a new medium for artists.
• Entertainment − Movies and games.
• Simulationandmodeling−Replacingphysicalmodelingandenactments

RASTER-SCAN DISPLAYS

In a raster scan system, the electron beam is swept across the screen, one
row at a time from top to bottom. As the electron beam moves across each
row, the beam intensity is turned on and off to create a pattern of illuminated
spots.

Picture definition is stored in memory area called the Refresh Buffer or


Frame Buffer. This memory area holds the set of intensity values for all the
screen points. Stored intensity values are then retrieved from the refresh
buffer and “painted” on the screen one row (scan line) at a time as shown in
the following illustration.

5
UNIT 1: BASICS OF COMPUTER GRAPHICS
Each screen point is referred to as a pixel (picture element) or pel. At the end
of each scan line, the electron beam returns to the left side of the screen to
begin displaying the next scan line.

Random-Scan Display

In this technique, the electron beam is directed only to the part of the screen
where the picture is to be drawn rather than scanning from left to right and
top to bottom as in raster scan. It is also called vector display, stroke- writing
display, orcalligraphic display.

Picture definition is stored as a set of line-drawing commands in an area of


memory referred to as the refresh display file.

To display a specified picture, the system cycles through the set of commands
in the display file, drawing each component line in turn.

6
UNIT 1: BASICS OF COMPUTER GRAPHICS
After all the line-drawing commands are processed, the system cycles back to
the first line command in the list.

Random-scan displays are designed to draw all the component lines of a


picture 30 to 60 times each second.

Flat Panel Display

The term flat–panel displays refers to a class of video devices that have
reduced volume, weight, and power requirements compared to a CRT. A
significant feature of flat-panel displayed is that they are thinner than CRTs,
and we can hang them on walls or wear them on our wrists.

Flat-panel displays into two categories: emissive displays and nonemissive


displays.
The emissive displays are devices that displays, and light-emitting diodes are
examples of emissivedisplays.

Nonemissive displays use optical effects to convert sunlight or light from


some other source into graphicspatterns.

7
UNIT 1: BASICS OF COMPUTER GRAPHICS
Light-emitting diode (LED)

A matrix of diodes is arranged to form the pixel positions in the display, and picture
definition is stored in refresh buffer. As in scan- line refreshing of a CRT, information
is read from the refresh buffer and converted to voltage levels that are applied to the
diodes to produce the light patterns in the display.

• The working of the LED depends on the quantum theory.The energy of the
photons is equal to the gap between the higher and lower level.
• The LED is connected in the forward biased, which allows the current to flows
in the forward direction. The flow of current is because of the movement of
electrons in the opposite direction.
• The recombination shows that the electrons move from the conduction band to
valence band and they emit electromagnetic energy in the form of photons. The
energy of photons is equal to the gap between the valence and the conduction
band.

Applications of Light Emitting Diodes

• used as a bulb in the homes andindustries


• used in the motorcycles and cars
• used in the mobile phones to display the message
• At the traffic light signals.

Advantages of LED’s

• The cost of LED’s is less and they are tiny.


• By using the LED’s the electricity is controlled.
• The intensity of the LED differs with the help of the microcontroller.
• The LED are available which emits light in the different colors like red, yellow,
green and amber.

8
UNIT 1: BASICS OF COMPUTER GRAPHICS
Disadvantages of LED

• The LED consumes more power as compared to LCD, and their cost is high. Also,
it is not used for making the large display.

Liquid-crystal display (LCD)

• It is combination of two states of matter, the solid and the liquid.


• LCD uses a liquid crystal to produce a visible image.
• LCD commonly used in systems, such as calculators and portable, laptop
computers.
• The basic structure of LCD should be controlled by changing the applied current.
• We must use a polarized light.
• Liquid crystal should able be to control both of the operation to transmit orcan
also able to change the polarized light.

Advantages of an LCD’s:

• LCD’s consumes less amount of power compared to CRT and LED


• LCDs are of low cost
• Provides excellent contrast
• LCD’s are thinner and lighter when compared to cathode ray tube and LED

Disadvantages of an LCD’s:

• Require additional light sources


• Range of temperature is limited for operation
• Low reliability
• Speed is very low

9
UNIT 1: BASICS OF COMPUTER GRAPHICS
Applications of Liquid Crystal Display
• Liquid crystal thermometer ,Optical imaging, Used in the medical applications

Plasma Display Panel

• A plasma display is a type of flat panel display .


• Plasma displays are also known as gas-plasmadisplays.
• A plasma display panel (PDP) is a type of flat panel display common to large TV
displays 30 inches (76 cm) orlarger.
• They are called "plasma" displays because they use small cells containing
electrically charged ionized gases, which are plasmas.
• Plasma displays are thinner than cathode ray tube ( CRT ) displays and brighter
than liquid crystal displays ( LCD).

Touch Screen

• A touch screen is a computer display screen that is also an input device. The
screens are sensitive to pressure; a user interacts with the computer by touching
pictures or words on the screen.
• There are three types oftouch screen technology:

❑ Resistive ❑ Surface wave ❑ Capacitive

Output primitives

• The Primitives are the simple geometric functions that are used to generate
various Computer Graphics required by the User. Some most basic Output
primitives are point-position (pixel), and a straight line.
• Line, polygon , marker , text.

Line Attributes

• A straight-line segment can be displayed with three basic attributes: color, width,
and style. Additionally, lines may be generated with other effects, such as pen and
brush strokes.
• To set line type attributes in a PHICS application program, a user invokes the
function :setLinetype (It)
where parameter It is assigned a positive integer value of 1,2,3, or 4 to generate lines
that are, respectively, solid, dashed, dotted, or dash-dotted.

10
UNIT 1: BASICS OF COMPUTER GRAPHICS

Marker Attributes

• A marker symbol display single character in a different color and in different sizes.
• We select marker type using the function. setMarkerType (mt) Where marker
type parameter mt set to an integer code.
• Typical codes for marker type are the integers 1 through 5, specifying,
respectively, a dot (.), a vertical cross (+), an asterisk (*), a circle (o), and a
diagonal cross (x). Displayed marker types centered on the marker coordinates.

Text Attributes

The attributes that can be assigned to text are common knowledge nowadays: Font
(e.g. Courier, Arial, Times, Broadway, …), style (normal, bold, italic, underlined, …),
size, text direction, color, alignment (left, right, centered, justified) and so on.

Attributes of Polygons

• A set of line segments joined end to end.


• Attributes: Fill color, Thickness, Fill pattern

Graphics Functions

Standard graphics formats allow images to be moved from machine to machine, while
standard graphics languages let graphics programs be moved from machine to
machine. For example, GKS, PHIGS and OpenGL are major graphics languages .
GDI and DirectX are the graphics languages in Windows.

11
UNIT 1: BASICS OF COMPUTER GRAPHICS

Putpixel function is to draw the pixel on the screen. Pixel is small dot on the screen.

Syntax:-putpixel(x co-orinate, y co-ordinate,COLOR);

Example: – putpixel(100,100,BLUE);

Rectangle function is used to draw the rectangle on the screen. X1,y1 are the lower
left co-ordinates of the rectangle and the x2,y2 are the upper right co- ordinates of the
rectangle.

Syntax:– rectangle(x1,,y1,x2,y2); Example:– rectangle(100,100,200,200);

Linefunction is used to draw the line on the screen.

Syntax: line(x1,y1,x2,y2);

Example:-line(100,100,200,100);

Circle function is used to draw the circle on thescreen

Syntax:– circle(x,y,radius); Example:-circle(100,100,50);

ellipse function is used to draw the ellipse on the screen.

Syntax:-ellipse(x, y, starting angle, ending angle, xradius, yradius);

Example:-ellipse(100,100,90,200,20,20);
Virtual reality

• Virtual reality (VR) means experiencing things


through our computers that don't really exist.

• A believable, interactive 3D computer-created world that you can explore so


you feel you really are there, both mentally and physically.

• Virtual reality essentially to make world Believable, Interactive, Computer-


generated, Explorable and Immersive(to be both believable and
interactive).

12
UNIT 1: BASICS OF COMPUTER GRAPHICS
Types of Virtual reality (VR) System

1. Windows on World(WoW)

– Also called Desktop VR.

– Using a conventional computer monitor to display the 3D virtual world.

2. Immersive VR

– Completely immerse the user's personal viewpoint inside the virtual 3D


world.

– The user has no visual contact with the physical word.

– Often equipped with a Head Mounted Display (HMD).

3. Telepresence

– A variation of visualizing complete computer generated worlds.

4. Mixed Reality(Augmented Reality)

- The seamless merging of real space and virtual space


Architecture of VR System

13
UNIT 1: BASICS OF COMPUTER GRAPHICS
▪ Input Processor
– Control the devices used to input information to the computer. The
object is to get the coordinate data to the rest of the system with minimal
lagtime.

– Keyboard, mouse, 3D position trackers, a voice recognition system, etc.

▪ Simulation Processor

– Core of a VR system.

– Takes the user inputs along with any tasks programmed into the world
and determine the actions that will take place in thevirtual world.

▪ Rendering Processor

– Create the sensations that are output to the user.

– Separate rendering processes are used for visual, auditory, haptic and
other sensory systems. Each renderer takes a description of the world
stat from the simulation process for each time step.

▪ World Database (World Description Files)


– Store the objects that inhabit the world, scripts that describe actions of
those objects.

What equipment do we need for virtual reality?

▪ Head-mounted displays (HMDs)


▪ Data gloves
▪ Binocular Omni-Orientation Monitor (BOOM)
▪ Cave Automatic Virtual Environment (CAVE)

Applications

▪ Entertainment
▪ Medicine
▪ Manufacturing

14
UNIT 1: BASICS OF COMPUTER GRAPHICS
▪ Education & Training

Augmented Reality (AR)

Augmented reality combines real and computer-based scenes and images to


deliver a unified but enhanced view of the world.

• There are three components needed in order to make an augmented- reality


system work:

– Head-mounted display

– Tracking system

– Mobile computing power • Future of Augmented Reality

• Military:

– The Office of Naval Research has sponsored AR research

– AR system could providetroops with vital information about their


surroundings.

• Medical:
– Superimpose an image from an MRI onto a patient’s body.

– This might allow surgeons to pinpoint a tumor to remove.

• Education:

– Used in labs where students can learn more about the experiments they
are participatingin.

• Gaming:

– ARQuake is an AR version of the popular game Quake.

Augmented Reality vs. Virtual Reality

15
UNIT 1: BASICS OF COMPUTER GRAPHICS

16
UNIT 2: RASTER SCAN GRAPHICS

Implement standard algorithms to draw various


CO2 :
graphics objects using C programs.

dx = X2 – X1 dy
= Y2 – Y1

if (abs(dx) > abs(dy))

length = abs(dx);

else length =
abs(dy);

Xinc = dx / (float) length; Yinc


= dy / (float) length;

1
UNIT 2: RASTER SCAN GRAPHICS

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

2
UNIT 2: RASTER SCAN GRAPHICS
(18 Marks)

3
UNIT 2: RASTER SCAN GRAPHICS

Basic concepts in line drawing:


We say these computers have vector graphics capability (the line is a vector). The process is turning
on pixels for a line segment is called vector generation and algorithm for them is known as vector
generation algorithm.

Problems of vector generation:

• Line is straight but width is no constant.


• Brightness of line dependent on orientation of the line.
• Calculate only an approximate linelength. Reduce the calculations using simple integer arithmetic.

DDA Algorithm
Digital Differential Analyzer (DDA) algorithm is the simple line generation algorithm which is explained
step by step here.

Step 1 − Get the input of two end points (X1, Y1) and (X2, Y2).
Step 2 − Calculate the difference between two end points.

Step 3 − Based on the calculated difference in step-2, you need to identify the number of steps to put
pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate.

Step 4 − Calculate the increment in x coordinate and y coordinate.

Step 5 − Put the pixel by successfully incrementing x and y coordinates accordingly and complete the
drawing of the line.

4
{ x = x + Xinc;
UNIT 2: RASTER SCAN GRAPHICS
y = y + Yinc;

putpixel(Round(x), Round(y));

5
UNIT 2: RASTER SCAN GRAPHICS

DDA Line Drawing Program

6
UNIT 2: RASTER SCAN GRAPHICS
#include<stdio.h>
#include<conio.h>
#include<graphics.h> void main()
{ int x1,y1,x2,y2,dx,dy,length,i; float
x,y,xinc,yinc;
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("Enter the starting coordinates");
scanf("%d%d",&x1,&y1); printf("Enter the
ending coordinates"); scanf("%d%d",&x2,&y2);
dx=x2-x1; dy=y2-y1; if(abs(dx)>abs(dy))
length=abs(dx); else length=abs(dy);
xinc=dx/(float)length; yinc=dy/(float)length;
x=x1; y=y1; putpixel(x,y,10);
for(i=0;i<length;i++)
{

7
UNIT 2: RASTER SCAN GRAPHICS
putpixel(x,y,10); x=x+xinc; y=y+yinc;

8
UNIT 2: RASTER SCAN GRAPHICS
delay(10);
} getch();
closegraph();
}
Advantages of DDA Algorithm
1. It is the simplest algorithm and it does not require special skills for implementation.
2. It is a faster method for calculating pixel positions.
Disadvantages of DDA Algorithm
1. Floating point arithmetic in DDA algorithm is still time-consuming.
2. The algorithm is orientation dependent. Hence end point accuracy is poor.

Bresenham's Line Drawing Algorithm


• It’s an accurate and efficient raster line generating Algorithm.
• Bresenham's line-drawing algorithm uses an iterative scheme.
• A key feature of the algorithm is that it requires only integer data and simple arithmetic. This
makes the algorithm very efficient and fast.

Procedure for Bresenham’s Line Drawing Algorithm:


1. Read line end points (x1,y1) and (x2,y2) such that they are not equal.
2. dx=|x2-x1| and dy=|y2-y1|
3. x=x1 and y=y1
4. e=2*dy-dx
5.i=1
6.plot (x,y)
7.while (e>0)
{
x=y+1

e=e-2*dx
}
x=x+1

9
UNIT 2: RASTER SCAN GRAPHICS
e=e+2*dy

10
UNIT 2: RASTER SCAN GRAPHICS
8. i=i+1
9. if(i<dx) then goto step 6. 10. Stop.

Program- Bresenham Line Drawing Algorithm -:


#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h> void main()
{
int gd=DETECT,gm=DETECT,length,dx,dy,x1,y1,x2,y2,e; float x,y;
clrscr(); printf("\n enter coordinates of x1,y1,x2,y2");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2); dx=x2-x1; dy=y2-y1;
e=2*dy-dx; x=x1; y=y1;
initgraph(&gd,&gm,"c://Turboc3//BGI"); while(x<=x2)
{ if(e<0)
{ x=x+1; y=y;
e=e+2*dy;
} else
{ x=x+1;

11
UNIT 2: RASTER SCAN GRAPHICS

12
UNIT 2: RASTER SCAN GRAPHICS
y=y+1; e=e+2*(dy-dx);
} putpixel(x,y,15);
} getch();
closegraph();
}
Problem: - Consider the line from (5, 5) to (13, 9). Use the Bresenham's algorithm to rasterize
the line. Solution:-
Evaluating steps 1 through 4 in the Bresenham’s algorithm we have, Given: - step 1:-
x1 = 5, y1 = 5 and x2 = 13, y2 = 9.
Step 2:- Δx = | 13 - 5| =8 Δy = | 9 - 5 | = 4
Step 3:- x = 5, y = 5
Step 4:- e = 2 * Δy - Δx = 2 * 4 - 8 = 0.
Tabulating the results of each iteration in the step 5 through 10.

13
UNIT 2: RASTER SCAN GRAPHICS

DDA Line Drawing Algorithm Bresenhams Line Drawing


Algorithm
Arithmetic uses floating points Integer points
Operations Uses multiplication and division in its Uses only subtraction and addition
operations. in its operations.
Speed slowly than Bresenhams algorithm faster than DDA
Accuracy & Efficiency not as accurate and efficient more efficient &much accurate
Drawing DDA algorithm can draw circles and Draw circles and curves with much
curves but that are not as accurate as more accuracy than DDA algorithm .
Bresenhams algorithm.

14
Round Off DDA algorithm round off the Bresenhams algorithm does not
coordinates to integer that is nearest round off but takes the incremental
to the line. value in its operation.

UNIT 2: RASTER SCAN GRAPHICS

Expensive Expensive Less Expensive


UNIT 2: RASTER SCAN GRAPHICS
Circle generating algorithm:
Symmetry of circle:
A circle is a geometric figure which is round, and can be divided into 360 degrees. A circle is a
symmetrical figure which follows 8-way symmetry.
8-Way symmetry: Any circle follows 8-way symmetry. This means that for every point (x,y) 8
points can be plotted. These (x,y), (y,x), (-y,x), (-x,y), (-x,-y), (-y,-x), (y,-x), (x,-y).

Drawing a circle: To draw a circle we need two things, the coordinates of the centre and the radius
of the circle.
Here r is the radius of the circle. If the circle has origin (0,0) as its centre then the above
equation can be reduced to x2 + y2 = r2

Bresenham’s Algorithm
We cannot display a continuous arc on the raster display. Instead, we have to choose the nearest
pixel position to complete the arc.
From the following illustration, you can see that we have put the pixel at (X, Y) location and
now need to decide where to put the next pixel − at N (X+1, Y) or at S (X+1, Y-1).

This can be decided by the decision parameter d.


= 0, then N(X+1, Y) is to be chosen as next pixel.
-1) is to be chosen as the next pixel.

Breshenham’s Algorithm for Circle Drawing

16
7
UNIT 2: RASTER SCAN GRAPHICS

18
1. Read the radius of circle.
UNIT 2: RASTER SCAN GRAPHICS
2. Calculate initial decision parameter di=3-2r
3. x=0 and y=r [initialize the starting point]
4. Do

{
5. Plot(x,y)//plot point(x,y) and other 7 points in all octant

if(di<0)then di=di+4x+6 else {


di=di+4(x-y)+10 y=y-1
}
x=x+1 }while(x<y);
6. stop

Program : bresenhams circle drawing algorihm

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
#include<graphics.h> void bressn(int,int,int); void plot(int,int,int,int); void plot(int xc,int yc,int x,int y)
{
putpixel(xc+x,yc+y,WHITE); putpixel(xc-x,yc+y,RED); putpixel(xc-x,yc-y,GREEN); putpixel(xc+x,yc-
y,YELLOW); putpixel(xc+y,yc+x,WHITE); putpixel(xc-y,yc+x,GREEN); putpixel(xc-y,yc-x,YELLOW);
putpixel(xc+y,yc-x,RED);
}
void bressn(int r,int xc,int yc)

20
UNIT 2: RASTER SCAN GRAPHICS

21
UNIT 2: RASTER SCAN GRAPHICS
{ int d,x,y; d=3-
(2*r); x=0; y=r;
while(x<y)
{ plot(xc,yc,x,y); x=x+1;
if(d<0)
{ d=d+(4*x)+6;
} else { y=y-1; d=d+4*(x-
y)+10;
} plot(xc,yc,x,y);
} } void main()
{ int gd,gm; int xc,yc,radius;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("\n enter xc,yc,radius");
scanf("%d%d%d",&xc,&yc,&radius);
bressn(xc,yc,radius); getch(); closegraph();
}
Example :

x y d
0 10 -17
1 10 -11
2 10 -1
3 10 13
4 9 -5
5 9 17
6 8 11
7 7 13

22
UNIT 2: RASTER SCAN GRAPHICS
Calculate the pixel position along the circle path with radius r=10 centered on the origin using

23
UNIT 2: RASTER SCAN GRAPHICS
Bresenham’s circle drawing algorithm from point (0,10) to point x=y. Solution:
The value of d is d=3-2r=3-2*10=-17
Tabulating results of step 4

Polygon:
A polygon is any 2-dimensional shape formed with straight lines. Triangles, quadrilaterals, pentagons,
and hexagons are all examples of polygons.
Types of polygon:
Every polygon is either convex or concave.
The difference between convex and concave polygons lies in the measures of their angles. For a
polygon to be convex, all of its interior angles must be less than 180 degrees.
Otherwise, the polygon is concave.

Inside-Outside Test
This method is also known as counting number method. While filling an object, we often need to
identify whether particular point is inside the object or outside it. There are two methods by which we
can identify whether particular point is inside an object or outside. -Even Rule
mber rule

Odd-Even Rule

24
UNIT 2: RASTER SCAN GRAPHICS
In this technique, we will count the edge crossing along the line from any point (x,y) to infinity. If the

25
UNIT 2: RASTER SCAN GRAPHICS
number of interactions is odd, then the point (x,y) is an interior point; and if the number of interactions
is even, then the point (x,y) is an exterior point. The following example depicts this concept.

From the above figure, we can see that from the point (x,y), the number of interactions point on the left
side is 5 and on the right side is 3. From both ends, the number of interaction points is odd, so the point
is considered within the object. Nonzero Winding Number Rule
This method is also used with the simple polygons to test the given point is interior or not.

Give the value 1 to all the edges which are going to upward direction and all other -1 as direction
values.

• Check the edge direction values from which the scan line is passing and sum up them.
• If the total sum of this direction value is non-zero, then this point to be tested is an interior point,
otherwise it is an exterior point.

• In the above figure, we sum up the direction values from which the scan line is passing then the
total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point.
Polygon filling:
• Polygon filling algorithms are classified as: seed fill algorithm and scan line algorithm.

26
UNIT 2: RASTER SCAN GRAPHICS

27
UNIT 2: RASTER SCAN GRAPHICS
• One way to fill polygon is to start from given “seed”, point known to be inside the polygon and
highlight outward from this point i.e. neighboring pixels until we encounter the boundary pixels.
This approach is called seed fill.
• Seed fill algorithm further classified as flood fill and boundary fill algorithm.
• Algorithms the fill interior defined regions are flood fill algorithms; those that fill boundary defined
regions are called boundary fill algorithm.
• Another approach to fill the polygon is to apply the inside test i.e. to check whether the pixels is
inside the polygon or outside the polygon and then highlight pixels which lie inside the polygon.
This approach is known as scan-line algorithm.

Flood Fill Algorithm


• Flood fill colors an entire area in an enclosed figure through interconnected pixels using a single
color. It is an easy way to fill color in the graphics. One just takes the shape and starts flood fill. The
algorithm works in a manner so as to give all the pixels inside the boundary the same color leaving
the boundary and the pixels outside.
• Flood fill algorithm is used for filling the interior of a polygon.
• Used when an area defined with multiple color boundaries.
• Start at a point inside a region− Replace a specified interior color (old color) with fill color • Fill the
4−connected or 8−connected region until all interior points being replaced.

4−Connected Regions From a given pixel, the region that you can get to by a series of 4 way moves
(north, south, east, west)
void fillcolor(int x,int y,int old_color,int new_color)
{
if(getpixel(x,y)==old_color)
{ delay(5);
putpixel(x,y,new_color);
fillcolor(x+1,y,old_color,new_color); fillcolor(x-1,y,old_color,new_color);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y-1,old_color,new_color);
}
}
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h> #include<dos.h>
void fillcolor(int,int,int,int);
void main()
{ int gd,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
rectangle(50,50,100,100); fillcolor(55,55,0,11);
getch();

28
UNIT 2: RASTER SCAN GRAPHICS
closegraph();

29
UNIT 2: RASTER SCAN GRAPHICS
}
void fillcolor(int x,int y,int old_color,int new_color)
{
if(getpixel(x,y)==old_color)
{ delay(5);
putpixel(x,y,new_color); fillcolor(x+1,y,old_color,new_color);
fillcolor(x-1,y,old_color,new_color);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y-
1,old_color,new_color);
}
}
8−Connected Regions From a given pixel, the region that you can get to by a series of 8-way moves
(north, south, east, west, NE, NW, SE, SW) void fillcolor(int x,int y,int old_color,int new_color)
{
if(getpixel(x,y)==old_color)
{ delay(5);
putpixel(x,y,new_color); fillcolor(x+1,y,old_color,new_color);
fillcolor(x-1,y,old_color,new_color);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y-
1,old_color,new_color); fillcolor(x+1,y+1,old_color,new_color);
fillcolor(x+1,y-1,old_color,new_color); fillcolor(x-1,y-
1,old_color,new_color); fillcolor(x-1,y+1,old_color,new_color);
}
}
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h> #include<dos.h>
void fillcolor(int,int,int,int);
void main()
{ int gd,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
rectangle(50,50,100,100); fillcolor(55,55,0,11);
getch(); closegraph();
}
void fillcolor(int x,int y,int old_color,int new_color) {

30
UNIT 2: RASTER SCAN GRAPHICS
if(getpixel(x,y)==old_color)

31
UNIT 2: RASTER SCAN GRAPHICS
{ delay(5);
putpixel(x,y,new_color); fillcolor(x+1,y,old_color,new_color);
fillcolor(x-1,y,old_color,new_color);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y-
1,old_color,new_color); fillcolor(x+1,y+1,old_color,new_color);
fillcolor(x+1,y-1,old_color,new_color); fillcolor(x-1,y-
1,old_color,new_color); fillcolor(x-1,y+1,old_color,new_color);
}
}

ADVANTAGE • Flood fill algorithm is simplest algorithm.


DISADVANTAGE • Flood fill algorithm is slow. • For large polygon flood fill algorithm is fail
because it requires a large frame.
Boundary Fill Algorithm
Start at a point inside the figure and paint with a particular color. Filling continues until a boundary
color is encountered.
• In boundary fill algorithm Recursive method is used to fill the whole boundary. • Start at a point inside
a region. • Paint the interior outward toward the boundary. • The boundary is specified in a single color.
4-connected boundary fill Algorithm:- boundary_fill(x, y,
f_colour, b_colour)
{
if(getpixel(x, y)! = b_colour && getpixel(x, y)! = f_colour)
{
putpixel(x, y, f_colour); boundary_fill(x + 1, y,
f_colour, b_colour); boundary_fill(x, y + 1, f_colour,
b_colour); boundary_fill(x -1, y, f_colour, b_colour);
boundary_fill(x, y – 1, f_colour, b_colour);
}
}
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h> #include<dos.h>
void boundary_fill(int,int,int,int);
void main()
{ int gd,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
rectangle(50,50,100,100); boundary_fill(55,55,6,15);

32
UNIT 2: RASTER SCAN GRAPHICS
getch(); closegraph(); }

33
UNIT 2: RASTER SCAN GRAPHICS
void boundary_fill(int x,int y,int fcolor,int bcolor)
{
if((getpixel(x,y)!=bcolor)&&(getpixel(x,y)!=fcolor))
{ delay(5); putpixel(x,y,fcolor);
boundary_fill(x+1,y,fcolor,bcolor);
boundary_fill(x-1,y,fcolor,bcolor);
boundary_fill(x,y+1,fcolor,bcolor);
boundary_fill(x,y-1,fcolor,bcolor);
}
}
8-connected boundary fill Algorithm:- boundary_fill(x, y,
f_colour, b_colour)
{
if(getpixel(x, y)! = b_colour && getpixel(x, y)! = f_colour)
{
putpixel(x, y, f_colour); boundary_fill(x + 1, y, f_colour,
b_colour); boundary_fill(x - 1, y, f_colour, b_colour);
boundary_fill(x, y + 1, f_colour, b_colour);
boundary_fill(x, y - 1, f_colour, b_colour);
boundary_fill(x + 1, y + 1, f_colour, b_colour);
boundary_fill (x - 1, y - 1, f_colour, b_colour);
boundary_fill(x + 1, y - 1, f_colour, b_colour);
boundary_fill(x - 1, y + 1, f_colour, b_colour);
}
}
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h> #include<dos.h>
void boundary_fill(int,int,int,int);
void main() { int gd,gm; detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
rectangle(50,50,100,100);
boundary_fill(55,55,6,15);
getch(); closegraph(); }
void boundary_fill(int x,int y,int fcolor,int bcolor) {

34
UNIT 2: RASTER SCAN GRAPHICS
if((getpixel(x,y)!=bcolor)&&(getpixel(x,y)!=fcolor))
{
delay(5);
putpixel(x,y,fcolor);
boundary_fill(x+1,y,fcolor,bcolor);
boundary_fill(x-1,y,fcolor,bcolor);
boundary_fill(x,y+1,fcolor,bcolor);
boundary_fill(x,y-1,fcolor,bcolor);
boundary_fill(x+1,y+1,fcolor,bcolor);
boundary_fill(x-1,y+1,fcolor,bcolor);
boundary_fill(x+1,y-1,fcolor,bcolor);
boundary_fill(x-1,y-1,fcolor,bcolor);
}
}

void fillcolor(int x,int y,int old_color,int boundary_fill(x, y, f_colour, b_colour)


new_color) {
{ if(getpixel(x, y)! = b_colour && getpixel(x, y)! =
if(getpixel(x,y)==old_color) f_colour)
{ {
putpixel(x,y,new_color); putpixel(x, y, f_colour);
fillcolor(x+1,y,old_color,new_color); boundary_fill(x + 1, y, f_colour, b_colour);
fillcolor(x-1,y,old_color,new_color); boundary_fill(x, y + 1, f_colour, b_colour);
fillcolor(x,y+1,old_color,new_color); boundary_fill(x -1, y, f_colour, b_colour);
fillcolor(x,y-1,old_color,new_color); boundary_fill(x, y – 1, f_colour, b_colour);
} }
} }

35
UNIT 2: RASTER SCAN GRAPHICS

void fillcolor(int x,int y,int old_color,int boundary_fill(x, y, f_colour, b_colour)


new_color) {
{ if(getpixel(x, y)! = b_colour && getpixel(x, y)! =
if(getpixel(x,y)==old_color) f_colour)
{ {
putpixel(x,y,new_color); putpixel(x, y, f_colour);
fillcolor(x+1,y,old_color,new_color); fillcolor(x- boundary_fill(x + 1, y, f_colour, b_colour);
1,y,old_color,new_color); boundary_fill(x - 1, y, f_colour, b_colour);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y- boundary_fill(x, y + 1, f_colour, b_colour);
1,old_color,new_color); boundary_fill(x, y - 1, f_colour, b_colour);
fillcolor(x+1,y+1,old_color,new_color); boundary_fill(x + 1, y + 1, f_colour, b_colour);
fillcolor(x+1,y-1,old_color,new_color); fillcolor(x- boundary_fill (x - 1, y - 1, f_colour, b_colour);
1,y-1,old_color,new_color); fillcolor(x- boundary_fill(x + 1, y - 1, f_colour, b_colour);
1,y+1,old_color,new_color); boundary_fill(x - 1, y + 1, f_colour, b_colour); }
} }
}

Scan Line Fill Algorithm


• To successfully fill in a polygon three main components will be used: Edge Buckets, an Edge
Table and an Active List.

• These components will contain an edge’s information, hold all of the edges that compose the
figure and maintain the current edges being used to fill in the polygon, respectively.

• When a scan line intersects an edge endpoint, it intersects two edges. Consider, Two cases: –
Case A: edges are monotonically increasing or decreasing, we should consider this as only ONE edge
intersection
– Case B: edges reverse direction at endpoint; we should consider this as TWO edge intersections

Stepwise Procedure
1. Read n, the number of vertices of polygon.
2. Read x and y coordinates of all vertices in array X[n] and y[n].
3. Find y max and y min
4. Store the initial x value (x1),y values (y1 and y2) and x increment dx from scan line to scan line for each edge
in the array edges[n] [4].
a. While doing this check that y1> y2, if not , interchange y1 and y2 corresponding x1 and x2 so that for
each edge, y1 represents its maximum y coordinate and y2 represents its minimum y coordinate.
36
UNIT 2: RASTER SCAN GRAPHICS
5. Sort the rows of array, edges[n] [4] in descending order of y1, descending order of y2, and ascending order of

37
UNIT 2: RASTER SCAN GRAPHICS
x2
6. Set y=y max
7. Find the active edges and update active edge list:
a. if ( y>y2 and y<y1) i {edge is active} b. Else i {edge is not active}
8. Compute the x intersects for all active edges for current y value. Initially x intersect is x1 and x intersects for
successive y values can be given as a. x(i+1)dxi+dx
b. where dx=-1/m and m=y2-y1/x2-x1 i.e. .slope of a line segment.
9. if x intersect is vertex i.e. x intersect =x1 and y=y1 then apply vertex test to check whether to consider one
intersect or two intersects. Store all x intersects in the x intersects array.
10. Store x intersects array in the ascending order.
11. Extract pairs of intersects from the sorted x intersect array.
12. Pass pairs of x values to line drawing routine to draw corresponding line segments.
13.-set y=y-1
14. Repeat steps 7 through 13 until y> ymin
15. Stop

Program:
Program:
#include <stdio.h>
#include <conio.h> #include <graphics.h> main()
{ int n,i,j,k,gd,gm,dy,dx; int x,y,temp;
int a[20][2],xi[20];
float slope[20]; clrscr(); printf("\n\n\tEnter the no. of edges of polygon : ");
scanf("%d",&n);
printf("\n\n\tEnter the cordinates of polygon :\n\n\n "); for(i=0;i<n;i++)
{
printf("\tX%d Y%d : ",i,i); scanf("%d %d",&a[i][0],&a[i][1]);
} a[n][0]=a[0][0]; a[n][1]=a[0][1]; detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi"); /*- draw polygon -*/ for(i=0;i<n;i++)
{ line(a[i][0],a[i][1],a[i+1][0],a[i+1][1]);

38
UNIT 2: RASTER SCAN GRAPHICS
} getch(); for(i=0;i<n;i++) { dy=a[i+1][1]-a[i][1]; dx=a[i+1][0]-a[i][0];

39
UNIT 2: RASTER SCAN GRAPHICS
if(dy==0) slope[i]=1.0; if(dx==0) slope[i]=0.0;
if((dy!=0)&&(dx!=0)) /*- calculate inverse slope -*/
{ slope[i]=(float) dx/dy;
}
} for(y=0;y< 480;y++)
{ k=0; for(i=0;i<n;i++)
{ if( ((a[i][1]<=y)&&(a[i+1][1]>y))|| ((a[i][1]>y)&&(a[i+1][1]<=y)))
{ xi[k]=(int)(a[i][0]+slope[i]*(y-a[i][1])); k++;
}
} for(j=0;j<k-1;j++) /*- Arrange x-intersections in order -*/ for(i=0;i<k-1;i++)
{ if(xi[i]>xi[i+1])
{ temp=xi[i]; xi[i]=xi[i+1]; xi[i+1]=temp;
} } setcolor(35); for(i=0;i<k;i+=2)
{
line(xi[i],y,xi[i+1]+1,y); getch();
}
}
}

Scan conversion
• The process of representing continuous graphics objects as a collection of discrete pixels is called scan
conversion. Scan conversion serves as a bridge between TV and computer graphics technology.

• Scan conversion or scan converting rate is a video processing technique for changing the vertical / horizontal
scan frequency of video signal for different purposes and applications.

• The device which performs this conversion is called a scan converter.

• The application of scan conversion: video projectors, cinema equipment, TV and video capture cards, standard
and HDTV televisions, LCD monitors, radar displays and many different aspects of picture processing.

40
UNIT 2: RASTER SCAN GRAPHICS
• There are two distinct methods for changing a picture's data rate:

41
UNIT 2: RASTER SCAN GRAPHICS

• Analog Methods (Non retentive, memory-less or real time method)

• This conversion is done using large numbers of delay cells and is appropriate for analog video.It may also be
performed using a specialized scan converter vacuum tube.

• In this case polar coordinates (angle and distance) data from a source such as a radar receiver, so that it can be
displayed on a raster scan (TV type) display.

• Digital methods (Retentive or buffered method)

• In this method, a picture is stored in a line or frame buffer with n1 speed (data rate) and is read with n2 speed.

Frame buffer:
• Each screen pixel corresponds to a particular entry in a 2D array residing in memory. This memory is called a
frame buffer or a bit map.

• The number of rows in the frame buffer equals to the number of raster lines on the display screen. The number
of columns in this array equals to the number of pixels on each raster line.

• Frame buffer is a large part of computer memory used to store display image. Different kind of memory can be
used for frame buffers like drums, disk or IC – shift registers.

• To generate a pixel of desired intensity to read the disk or drum. The information stored in disk or drum is in
digital for, hence it is necessary to convert it into analog from using DAC and then this analog signal is used to
generate the pixel.

Character Generation

42
UNIT 2: RASTER SCAN GRAPHICS
• Most of the times characters are builts into the graphics display devices, usallay as hardware but sometimes

43
UNIT 2: RASTER SCAN GRAPHICS
through software.

• There are basic three methods:


– Stroke method
– Starbust method
– – Bitmap method
• 1. Stroke method

• This method uses small line segments to generate a character.

• The small series of line segments are drawn like a strokes of a pen to form a character as shown in figure.

• We can build our own stroke method.


• By calling a line drawing algorithm.

• Here it is necessary to decide which line segments are needed for each character and

• Then drawing these segments using line drawing algo.


• This method supports scaling of the character.
• It does this by changing the length of the line segments used for character drawing.

2. Starbust method
• In this method a fix pattern of line segments are used to generate characters.

• As shown in figure, there are 24 line segments.

• Out of 24 line segments, segments required to display for particular character, are highlighted

• This method is called starbust method because of its characteristic appearance.

44
UNIT 2: RASTER SCAN GRAPHICS

45
UNIT 2: RASTER SCAN GRAPHICS
This method of character generation has some disadvantages. They are

46
UNIT 2: RASTER SCAN GRAPHICS
1. The 24-bits are required to represent a character. Hence more memory is required 2. Requires code conversion
software to display character from its 24-bit code
3. Character quality is poor. It is worst for curve shaped characters.

3. Bitmap Method

• Also known as dot matrix because in this method characters are represented by an array of dots in the matrix
form.

• It’s a two dimensional array having columns and rows: 5 X 7 as shown in figure.

• 7 X 9 and 9 X 13 arrays are also used.

• Higher resolution devices may use character array 100 X 100.

47
UNIT 3: OVERVIEW OF TRANSFORMATION
Q. What is meant by transformations?

ANS. A transformation is an operation that changes the position, size, or


orientation of an object. In computer graphics, transformations are used to
manipulate objects on the screen.

Q. What is Two-dimensional transformation?

ANS. A 2D transformation is a transformation that takes place in a


twodimensional plane. The most common types of 2D transformations are
translation, scaling, and rotation.

In many applications, changes in orientations, size, and shape are


accomplished with geometric transformations that alter the coordinate
descriptions of objects.
Basic geometric transformations are:
These are most useful and most used.
1.Translation (Position)
2.Rotation (Orientation)
3. Scaling (Size)

Other transformations: These transformations are useful in certain


applications.
Reflection (Mirror) Shear
(Size)

Q. Define the following terms: 1. Translation 2. Scaling 3.


Rotation 4. Reflection 5.Shearing

ANS. 1. Translation: A translation is a transformation that moves an


object from one place to another. It is defined by a vector that
specifies the amount of movement in each direction.

2.Scaling: A scaling transformation changes the size of an object. It


is defined by a scale factor that specifies the amount of increase or
decrease in size.

3.Rotation: A rotation transformation changes the orientation of an


object. It is defined by an angle of rotation and a centre of rotation.
4.Reflection: A reflection transformation flips an object over a line or
axis. The axis of reflection is the line or axis that the object is
reflected over.

5.Shearing: A shearing transformation distorts an object by


stretching it in one direction while shrinking it in another direction.
The direction of the shear is determined by the vector that is
applied to the object.

2D Translation

Q. What is 2d translation?

ANS. A 2D translation is a transformation that moves an object from one


position to another in a two-dimensional plane. It is defined by a vector
that specifies the amount of movement in each direction. For example, a
translation of (2, 3) would move an object 2 units to the right and 3 units
up. In mathematical terms, a 2D translation can be represented by a
matrix.
The matrix has the following form:

[1 0 tx]
[0 1 ty]

where tx is the amount of movement in the x-direction and ty is the


amount of movement in the y-direction.

- Moves points to new locations by adding translation amounts to the


coordinates of the points.
• Initial Position point P (x, y) • The new point P’
(x’, y’) Where, x’ = x + tx y’ = y + ty tx and ty is the
displacement
in x and y respectively.
The translation pair (tx, ty) is called a translation vector
or shift vector.

Matrix Representation

OR P’ = P + T
Program: Write a program for 2D Translation of a Triangle.
#include<stdio.h>
#include<conio.h> #include<graphics.h>
#include<process.h> #include<math.h>
int x1,y1,x2,y2,x3,y3,mx, my;
UNIT 3: OVERVIEW OF TRANSFORMATION

void draw();
void tri(); void
main()
{
int gd=DETECT,gm; int c; initgraph(&gd,&gm,"c:\\turboc3\\bgi ");
printf("Enter the 1st point for the triangle:");
scanf("%d%d",&x1,&y1); printf("Enter the 2nd
point for the triangle:"); scanf("%d%d",&x2,&y2);
printf("Enter the 3rd point for the triangle:");
scanf("%d%d",&x3,&y3);

cleardevice(); draw(); getch();


tri(); getch(); }

void draw()
{
line(x1,y1,x2,y 2);
line(x2,y2,x3,y
3); line(x3,y3,x1,y
1);
} void tri() {
int x,y,a1,a2,a3,b1,b2,b3; printf("Enter the
Transaction coordinates");
scanf("%d%d",&x, &y);
cleardevice(); a1=x1+x;
b1=y1+y; a2=x2+x;
b2=y2+y;
UNIT 3: OVERVIEW OF TRANSFORMATION

a3=x3+x; b3=y3+y;
line(a1,b1,a2,b
2);
line(a2,b2,a3,b
3);
line(a3,b3,a1,b
1); }

Q. What is meant by rotation?

Ans.
1. Rotation is a fundamental transformation in computer graphics that
involves rotating an object around a fixed point by a certain angle. It
is commonly used to create animations, simulate physical systems,
and manipulate images.
2. In 2D graphics, rotation can be achieved by multiplying the
coordinates of each point in the object by a rotation matrix.
3. The rotation matrix is defined by the angle of rotation and the axis
of rotation.
4. For example, a 90-degree clockwise rotation can be achieved by
multiplying the coordinates by the matrix [0 -1; 1 0]. This will flip the
x and y coordinates and rotate the object by 90 degrees. x = r cos
(φ)

y = r sin (φ)

x’ = r cos (φ + θ)

y’ = r sin (φ + θ)

x’ = r cos (φ + θ)
= r cos(φ) cos(θ) – r sin(φ) sin(θ)
= x cos(θ) – y sin(θ)

y’ = r sin (φ + θ) = r sin(φ) cos(θ) + r cos(φ)sin(θ) = y cos(θ) + x sin(θ)


So, x’ = x cos(θ) – y sin(θ) and y’ = y cos(θ) + x sin(θ) Representing
the above equation in matrix form,

Where R is the rotation matrix

P’ = P. R

For positive rotation angle, we can use the above rotation matrix.

However, for negative angle rotation, the matrix will change as shown
below.

Program: Write a program for 2D Rotation of a Triangle

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<process.h> #include<math.h>
void triangle(int x1,int y1,int x2,int y2,int x3,int y3);
void Rotate(int x1,int y1,int x2,int y2,int x3,int y3); void
main()
{
int gd=DETECT,gm;
int x1,y1,x2,y2,x3,y3;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("Enter the 1st point for the triangle:"); scanf("%d%d",&x1,&y1);
printf("Enter the 2nd point for the triangle:"); scanf("%d%d",&x2,&y2);
printf("Enter the 3rd point for the triangle:");
scanf("%d%d",&x3,&y3);
triangle(x1,y1,x2,y2,x3,y3);
getch(); cleardevice();
Rotate(x1,y1,x2,y2,x3,y3);
setcolor(1);
triangle(x1,y1,x2,y2,x3,y3);
getch();
}
void triangle(int x1,int y1,int x2,int y2,int x3,int y3)
{
line(x1,y1,x2,y2); line(x2,y2,x3,y3);
line(x3,y3,x1,y1);
}
void Rotate(int x1,int y1,int x2,int y2,int x3,int y3)
{
int x,y,a1,b1,a2,b2,a3,b3,p=x2,q=y2; float
Angle;
printf("Enter the angle for rotation:");
scanf("%f",&Angle); cleardevice();
Angle=(Angle*3.14)/180; a1=p+(x1-
p)*cos(Angle)-(y1-q)*sin(Angle);
b1=q+(x1-p)*sin(Angle)+(y1-q)*cos(Angle);
a2=p+(x2-p)*cos(Angle)-(y2-q)*sin(Angle);
b2=q+(x2-p)*sin(Angle)+(y2-q)*cos(Angle);
a3=p+(x3-p)*cos(Angle)-(y3-q)*sin(Angle);
b3=q+(x3-p)*sin(Angle)+(y3-q)*cos(Angle);
printf("Rotate"); triangle(a1,b1,a2,b2,a3,b3);
}
Let us suppose you want to rotate it at the angle θ. After rotating it to a
new location, you will get a new point P’ (X’, Y’).
Counter clockwise(anticlockwise) rotation
Clockwise Rotation

Homogeneous co-ordinates for rotation :-

Example:- Perform 450 rotation of triangle A(0,0) , B(1,1), C(5,2) about


origin
Rotation about an arbitrary point
Reference point of rotation is other than origin call as rotation
about an arbitrary. To rotate objects about an arbitrary point
(xp, yp) carry out three steps:
1. Translate point(xp, yp) to the origin
2. Rotate it about the origin
3. Retranslate the center of rotation back to its original position.
Example:- Perform a 450 rotation of triangle A(0,0),B(1,1) C(5,2) about
P(1,-1)

Shear
A transformation that slants the shape of an object is called the shear
transformation. There are two shear transformations X-Shear and
YShear. One shifts X coordinates values and other shifts Y coordinate
values. However; in both the cases only one coordinate changes its
coordinates and other preserves its values. Shearing is also termed as
Skewing.
X-Shear
The X-Shear preserves the Y coordinate and changes are made to X
coordinates, which causes the vertical lines to tilt right or left as shown in
below figure.

The transformation matrix for X-Shear can be represented as −

X' = X + Shx . Y
Y’ = Y

Y-Shear
The Y-Shear preserves the X coordinates and changes the Y coordinates
which causes the horizontal lines to transform into lines which slopes up
or down as shown in the following figure.

The Y-Shear can be represented in matrix from as −


Y’ = Y + Shy . X X’
=X

Shearing Relative to other reference line


We can apply x shear and y shear transformations relative to other
reference line. In x shear transformation we can use y reference line and
in y shear we can use x reference line.

1 00 shx 1 0
X shear with y reference line: - shx*yref 0 1

Y shear with x reference line: 1 shy 0


0 1 0
0 -shy*xref 0

Apply the shearing transformation to square with A(0,0),B(1,0),C(1,1),


D(0,1) as given below
a) Shear parameter value of 0.5 relative to the line yref=-1
b) Shear parameter value of 0.5 relative to the line xref=-1
Reflection
Reflection is the mirror image of original object. In other words, we can
say that it is a rotation operation with 180°. In reflection transformation,
the size of the object does not change.
The following figures show reflections with respect to X and Y axes, and
about the origin respectively.
Three Dimensional Transformation Translation
1 0 0 0
0 1 0 0
T= 0 0 1 0 tx ty
tz 1

Scaling
Sx 0 0 0
S= 0 Sy 0 0
0 0 Sz 0
0 0 0 1

Rotation about X axis


1 0 0 0
Rx= 0 cosθ sinθ 0

0 -sinθ cosθ 0
0 0 0 1

Rotation about Y
axis

cosθ 0 -sinθ 0 Rotation about Z axis


Rx= 0 1 0
0 sinθ 0 cosθ sinθ 0 0
cosθ 0 -sinθ cosθ
0 0 0 1 1 0 Rx=
0 0 1 0
0 0 0 1

Projection
Projection in computer graphics means the transformation of a
threedimensional (3D) area into a two-dimensional (2D) area.
Parallel Projection
Parallel projection discards z-coordinate and parallel lines from each
vertex on the object are extended until they intersect the view plane. In
parallel projection, we specify a direction of projection instead of center of
projection.
In parallel projection, the distance from the center of projection to project
plane is infinite. In this type of projection, we connect the projected
vertices by line segments which correspond to connections on the
original object.

Perspective Projection
The perspective projection on the other hand produces realistic views but
does not preserve relative proportions. In perspective projection, the lines
of projections are not parallel. Instead they all converge at a single point
called center of projection or projection reference point.

Types of Parallel Projection

Orthographic Projection
In orthographic projection the direction of projection is normal
(perpendicular) to the projection of the plane.
Classified as Axonometric orthographic projection
The orthographic projection can display more than one face of an object
is called axonometric orthographic projection.
Isometric: - All the principle axis are foreshortened equally.
Dimetric :- Two principle axis are foreshortened equally.
Trimetric: - All the three principle axis are foreshortened unequally.
Multi-view orthographic projection
Top view
Front view
Side view

Oblique Projection
In oblique projection, the direction of projection is not normal to the
projection of plane. In oblique projection, we can view the object better
than orthographic projection.
There are two types of oblique projections − Cavalier and Cabinet. The
Cavalier projection makes 45° angle with the projection plane. The
projection of a line perpendicular to the view plane has the same length
as the line itself in Cavalier projection. In a cavalier projection, the
foreshortening factors for all three principal directions are equal.
The Cabinet projection makes 63.4° angle with the projection plane. In
Cabinet projection, lines perpendicular to the viewing surface are
projected at ½ their actual length. Both the projections are shown in the
following figure −
.

Perspective Projection
In perspective projection, the distance from the center of projection to
project plane is finite and the size of the object varies inversely with
distance which looks more realistic.
The distance and angles are not preserved and parallel lines do not
remain parallel. Instead, they all converge at a single point called
Vanishing point. There are 3 types of perspective projections which are
shown in the following chart.
• One point perspective projection is simple to draw.
• Two point perspective projection gives better impression of depth.
• Three point perspective projection is most difficult to draw.

The following figure shows all the three types of perspective projection −
UNIT IV : Windowing And Clipping (14 Marks)

CO 5: Implement Various Clipping Algorithms


Window:
1. A world-coordinate area selected for display is called a window.
2. It consists of a visual area containing some of the graphical user interface of the
program it belongs to and is framed by a window decoration.
3. A window defines a rectangular area in worldcoordinates.
Viewport:

1. An area on a display device to which a window is mapped is called a viewport.


2. A viewport is a polygon viewing region in computer graphics. The viewport is an area
expressed in rendering-device-specific coordinates, e.g. pixels for screen coordinates,
in which the objects of interest are going to be rendered.
Window to viewport transformation:
The window defines what is to be viewed; the viewport defines where it is to be displayed.
1. Window-to-Viewport transformation is the process of transforming a two-
dimensional, world-coordinate scene to device coordinates.
2. In particular, objects inside the world or clipping window are mapped to the
viewport. The viewport is displayed in the interface window on the screen.

Figure: window and viewport

The picture is stored in the computer memory using any convenient Cartesian co-ordinate system,
referred to as World Co-Ordinate System (WCS). However, when picture is displayed on the display
device it is measured in Physical Device Co-Ordinate System (PDCS) corresponding to the
displaydevice.

The viewing transformation which maps picture co-ordinates in the WCS to display co-ordinates in
PDCS is performed by the following transformations.

• Converting world co-ordinates to viewing co-ordinates.


• Normalizing viewing co-ordinates.

• Converting normalized viewing co-ordinates to device co-ordinates.

Figure: Two-dimensional viewing-transformation pipeline.

The steps involved in viewing transformation:-


1. Construct the scene in world co-ordinate using the output primitives and attributes.
2. Obtain a particular orientation for the window by setting a two-dimensional viewing
co-ordinate system in the world co-ordinate plane and define a window in the viewing
co-ordinate system.
3. Use viewing co-ordinates reference frame to provide a method for setting up arbitrary
orientations for rectangular windows.
4. Once the viewing reference frame is established, transform descriptions in world co-
ordinates to viewing co-ordinates.
5. Define a view port in normalized co-ordinates and map the viewing co-ordinates
description of the scene to normalized co-ordinates.
6. Clip all the parts of the picture which lie outside theviewport.

Line clipping:
In line clipping, we will cut the portion of line which is outside of window and keep only
the portion that is inside the window.

Cohen Sutherland Line Clipping Algorithm


Different cases which are to be consider before clipping line are,
i) Completely inside. ii) Completely outside. iii) Partly inside.

As shown in fig three lines are given in which one line is inside window so that is displayed,
second line is completely outside so it is discarded after clipping, and third line is clipped as it
is partially in so that much part is displayed and remaining part is discarded.
Line clipping in given window.

Algorithm:

1. Read 2 end points of line as p1(x1,y1) and p2(x2,y2)

2. Read 2 corner points of the clipping window (left-top and right-bottom) as (wx1,wy1) and

(wx2,wy2) 3. Assign the region codes for 2 endpoints p1 and p2 using following steps:- initialize

code with 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 forvisibility of line

a. If region codes for both endpoints are zero then line is completely visible. Draw the line
go to step 9.

b. If region codes for endpoints are not zero and logical ANDing of them is also nonzero
then line is invisible. Discard the line and move to step 9.

c. If it does not satisfy 4.a and 4.b then line is partially visible.

5. Determine the intersecting edgeof clipping windowas follows:-


a. If region codes for both endpoints are nonzero find intersection points p1’ and p2’ with
boundary edges.

b. If region codes for any one end point is non zero then find intersection point p1’ or p2’.

6. Divide the line segments consideringintersection points.


7. Reject line segmentif any end point of line appears outside of any boundary.

8. Draw the clipped line segment.

9. Stop.

Program:

#include<stdio.h>
#include<graphics.h
> void main()
{
int gd=DETECT, gm; float
i,xmax,ymax,xmin,ymin,x11,y11,x22,y22,m;
float a[4],b[4],c[4],x1,y1; clrscr();
initgraph(&gd,&gm,"c:\\turboc3\\bgi"
);
printf("\nEnter the bottom-left coordinate of viewport:
"); scanf("%f %f",&xmin,&ymin); printf("\nEnter the
top-right coordinate of viewport: ");
scanf("%f %f",&xmax,&ymax);
rectangle(xmin,ymin,xmax,ymax); printf("\nEnter the
coordinates of 1st end point of line:
"); scanf("%f %f",&x11,&y11); printf("\nEnter the
coordinates of 2nd endpoint of line: "); scanf("%f
%f",&x22,&y22); line(x11,y11,x22,y22);
for(i=0;i<4;i++)
{ a[i]=0;
b[i]=0;
}
m=(y22-y11)/(x22-x11);
if(x11<xmin) a[3]=1;
if(x11>xmax) a[2]=1;
if(y11<ymin) a[1]=1;
if(y11>ymax) a[0]=1;
if(x22<xmin) b[3]=1;
if(x22>xmax) b[2]=1;
if(y22<ymin) b[1]=1;
if(y22>ymax) b[0]=1;
printf("\nRegion code of 1st pt
"); for(i=0;i<4;i++)
{printf("%f",a[i]);}
printf("\nRegion code of 2nd pt
"); for(i=0;i<4;i++)
{printf("%f",b[i]);
} printf("\nAnding
: ");
for(i=0;i<4;i++)
{c[i]=a[i]&&b[i];}
for(i=0;i<4;i++)
printf("%f",c[i]);
getch();
if((c[0]==0)&&(c[1]==0)&&(c[2]==0)&&(c[3]==0))
{
if((a[0]==0)&&(a[1]==0)&&(a[2]==0)&&(a[3]==0)&&
(b[0]==0)&&(b[1]==0)&&(b[2]==0)&&(b[3]==0))
{ clrscr(); clearviewport(); printf("\nThe line is totally
visible\nand not a clipping candidate");
rectangle(xmin,ymin,xmax,ymax); line(x11,y11,x22,y22);
getch();
} else
{
clrscr();
clearviewport(); printf("\nLine is
partially visible");
rectangle(xmin,ymin,xmax,ymax);
line(x11,y11,x22,y22); getch();
if((a[0]==0)&&(a[1]==1))
{
x1=x11+(ymin-
y11)/m; x11=x1;
y11=ymin;
}
else if((b[0]==0)&&(b[1]==1))
{
x1=x22+(ymin-y22)/m;
x22=x1;
y22=ymin;
}
if((a[0]==1)&&(a[1]==0))
{
x1=x11+(ymax-y11)/m;
x11=x1; y11=ymax;
}
else if((b[0]==1)&&(b[1]==0))
{
x1=x22+(ymax-y22)/m; x22=x1;
y22=ymax;
}
if((a[2]==0)&&(a[3]==1))
{
y1=y11+m*(xmin-x11);
y11=y1; x11=xmin;
}
else if((b[2]==0)&&(b[3]==1))
{
y1=y22+m*(xmin-
x22); y22=y1; x22=xmin;
}
if((a[2]==1)&&(a[3]==
0))
{
y1=y11+m*(xmax-x11); y11=y1;
x11=xmax;
}
else if((b[2]==1)&&(b[3]==0))
{
y1=y22+m*(xmax-x22);
y22=y1;
x22=xmax; } clrscr();
clearviewport(); printf("\nAfter
clippling:");
rectangle(xmin,ymin,xmax,ymax);
line(x11,y11,x22,y22);
getch();
}
} else
{
clrscr(); clearviewport();
printf("\nLine is
invisible");
rectangle(xmin,ymin,xmax,ymax);
getch();
}
closegraph(); getch();
}
Cyrus–Beck algorithm

Convex region, boundary point and inner normal

Cyrus and Beck developed an algorithm for clipping to arbitrary convex regions. Cyrus-
Beck algorithm uses the normal vector for determining whether a point is inside, on, or
outside a window. Consider a convex planar polygon R. Consider the parametric
representation of a line from P1 to P2.

If ‘f ’ is a boundary point of the convex region R and n is an inner normal for one of its
boundaries, then for any particular value of t, i.e. any particular point on line P1P2.
Together these conditions show that for a convex polygon, an infinite line, which
intersects the boundary of the region, does so at precisely two points. Further, these
two points do not lie on the same boundary edge. Thus n• [P(t) –f] = 0 has only one
solution. If the point ‘f ’ lies in the boundary edge for which n is the inner normal,
then that point (t) on the line P(t) which satisfies this condition is the intersection
of the line and the boundary edge.
Algorithm:
Liang-Barsky Line Clipping

• The ideas for clipping line of Liang-Barsky and Cyrus-Beck are the same.
The only difference is Liang-Barsky algorithm has been optimized for an
upright rectangular clip window.
• Liang and Barsky have created an algorithm that uses floating-point
arithmetic but finds the appropriate end points with at most four
computations.
• This algorithm uses the parametric equations for a line and solves four
inequalities to find the range of the parameter for which the line is in the
viewport.

1. parametric equation of line segment:


X = X1 + U ΔX
Y = Y1 + U ΔY
Where, ΔX = X2 – X1 and ΔY = Y2 – Y1
2. Using these equations Cyrus and Beck developed an algorithm that is generated more
efficient than the Cohen Sutherland algorithm.
3. Later Liang and Barsky independently devised an even faster parametric line clipping
algorithm.

4. In the Liang-Barsky approach we first the point clipping condition in parametric form:

Xmin≤X1+UΔX≤XmaxXmin≤X1+UΔX≤Xmax

Ymin≤Y1+UΔY≤YmaxYmin≤Y1+UΔY≤Ymax

5. Each of these four inequalities can be expressed as: μpk ≤ qk for k=1,2,3,4
6. The parameters p & q are defined as:
p1 = -ΔX and q1 = X1 – Xmin (Left Boundary)
p2 = ΔX and q2 = Xmax - x1 (Right Boundary)
P3 = -ΔY and q3 = Y1- Ymin (Bottom Boundary)
P4 = ΔY and q4 = Ymax - y1 (TopBoundary)
7. If a line is parallel to a view window boundary, the p value for that boundary is zero.
8. If the line is parallel to the X axis, for example then p1 and p2 must be zero.
o Given pk = 0, if qk < 0 then line is trivially invisible because it is outside view
window.
o Given pk = 0, if qk > 0 then the line is inside the corresponding window
boundary.
9. When pk < 0, as U increase line goes from the outside to inside i.e. entering.
10. When pk > 0, linegoes from inside to outside i.e. exiting.
11. If there is a segment of line inside the clip region, a sequence of infinite line
intersections must go entering, entering, exiting, and exiting as shown in figure.
Algorithm:
Advantages

1. More efficient than other algorithms as line intersection with boundaries calculations are reduced.

2. Intersections of line are computed onlyonce.

Program for Line Clipping Using Liang Barsky Algorithm:

#include<stdio.h>
#include<conio.h>
#include< graphics.h>
#include<dos.h>
#define ROUND(a)((int)(a+0.5))
int cliptest(float p,float q,float *u1,float *u2)
{ float r; int
retval=1;
if(p<0.0)
{
r=q/p;
if(r>*u2
)
retval=0;
if(r>*u1)
*u1=r;
}
else if(p>0.0)
{
r=q/p;
if(r<*u1
)
retval=0 ;
if(r<*u2)
*u2=r;
}
else if(q<0.0)
retval=0
; return(retval);
}
void clipline(int minx,int miny,int maxx,int maxy,int x1,int y1,int x2,int y2)
{
float u1=0.0,u2=1.0,dx=x2-x1,dy;
if(cliptest(-dx,x1- minx,&u1,&u2))
if(cliptest(dx,maxx- x1,&u1,&u2))
{
dy=y2-y1; if(cliptest(-dy,y1-
miny,&u1,&u2))
if(cliptest(dy,maxy-
y1,&u1,&u2))
{
if(u2<1.0)
{
x2=x1+u2*dx; y2=y1+u2*dy;
}
if(u1>0.0)
{
x1+=u1*dx;
y1+=u1*dy
;
}
line(x1,y1,x2,y2);
}
}
}
void main()
{ int
gdriver=DETECT,gmode,x1,y1,x2,y2,minx,miny,maxx,maxy;
initgraph(&gdriver,&gmode,"c:\\turboc3\\bgi"); clrscr();
printf("Enter the min & max x values: "); scanf("%d
%d",&minx,&maxx); printf("Enter the min & max y values:
"); scanf("%d %d",&miny,&maxy);
printf("Enter the first endpoint: ");
scanf("%d %d",&x1,&y1);
printf("Enter the second endpoint:
");
scanf("%d %d",&x2,&y2);
clrscr();
printf("Before Clipping");
line(x1,y1,x2,y2);
rectangle(minx,maxy,maxx,miny
); getch(); clrscr(); printf("After
Clipping");
clipline(minx,miny,maxx,maxy,x1,y1,x2,y2 );
rectangle(minx,maxy,maxx,miny); getch();
}

Midpoint subdivision algorithm:

Midpoint subdivision algorithm is an extension of the Cyrus Beck algorithm. This algorithm is
mainly used to compute visible areas of lines that are present in the view port are of the sector or
the image.
Algorithm :

1) Read two end points of line P1 (x1,y1) and P2 (x2,y2).


2) Read corners of window (Wx1, Wy1) and (Wx2, Wy2).
3) Assign region codes for P1 and P2. A region code is a 4 digit bit code which indicates one
of nine regions having the end point of line.
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 visibility of line P1P2
a) If region codes for both end points P1 and P2 are 0 = > Line is completely visible.
Draw Line and Go to Step 3.
b) If region codes for both end points P1 and P2 are not 0 and logical ANDing of them
is also not zero = > Line is completely invisible. Reject line and Go to Step 3. c) If a) and
b) both are not satisfied, line is partially visible.
5) Divide partially visible line segments to equal parts and repeat steps 3 through 5 for
both sub divided line segments until you get completely visible and completely invisible
line segments.
6) Stop.

Program:

//MIDPOINT SUBDIVISION LINE CLIPPING


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>
#include<math.h>
#include<graphics.h>
typedef struct
coordinate
{ int x,y; char
code[4];
}PT; void
drawwindow();
void drawline (PT p1,PT p2,int cl); PT
setcode(PT p);

int visibility (PT p1,PT


p2); PT resetendpt (PT
p1,PT p2); main()
{
int gd=DETECT, gm,v; PT
p1,p2,ptemp;
initgraph(&gd,&gm,"C :\\turboc3\\BGI ");
cleardevice(); printf("\n\n\t\tENTER END-
POINT 1 (x,y):
"); scanf("%d%d",&p1.x,&p1.y); printf("\n\n\t\tENTER
END-POINT 2 (x,y):
"); scanf("%d%d",&p2.x,&p2.y);
cleardevice(); drawwindow();
getch();
drawline(p1,p2,15
); getch();
cleardevice(); 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)
{
case 0: /* Line conpletely 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;
}
}
void drawwindow()
{
setcolor(RED);
line(150,100,450,100
);
line(450,100,450,400
);
line(450,400,150,400
);
line(150,400,150,100
);
}
void drawline (PT p1,PT p2,int cl)
{
setcolor(cl); line(p1.x,p1.y,p2.x,p2.y)
;
}
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.code[1]='1'; /*
BOTTOM
*/ else
ptemp.code[1]='0';
if (p.x>=450)
ptemp.code[2]='1'; /* RIGHT
*/ else ptemp.code[2]='0';
if (p.x<=150) /* LEFT */
ptemp.code[3]='1'; else
ptemp.code[3]='0';
ptemp.x=p.x; ptemp.y=p.y;
return(ptemp);
}

int visibility (PT p1,PT p2)


{ int i,flag=0;
for(i=0;i<4;i+
+
)
{
if((p1.code[i]!='0')||(p2.code[i]!='
0')) flag=1;
}
if(flag==0)
return(0);
for(i=0;i<4;i++
)
{
if((p1.code[i]==p2.code[i])
&&(p1.code[i]=='1')) flag=0;
}
if(flag==0
)
return(1);
return(2);
}
Polygon clipping:
There are several well-known polygon clipping algorithms, each having its strengths and weaknesses.
The oldest one (from 1974) is called the Sutherland-Hodgman algorithm. In its basic form, it is relatively simple.
It is also very efficient in two important cases, one being when the polygon is completely inside the boundaries,
and the other when it's completely outside. Sutherland - Hodgeman Polygon Clipping:

Each edge of the polygon must be tested against each edge of the clip rectangle.
New edges must be added, and existing edges must be discarded, retained, or divided.
Multiple polygons may result from clipping a single polygon. We need an organized way to
deal with all these cases.

Steps of Sutherland-Hodgeman's polygon clipping algorithm:


i. Polygons can be clipped against each edge of the window one at a time.
ii. Vertices which are kept after clipping against one window edge are saved for clipping
against the remaining edges. iii. Note that the number of vertices usually changes and
will often increases.
Four Cases of polygon clipping against one Edge:
The clip boundary determines a visible and invisible region. The edges from vertex can be
one of four types:
Case 1: If the first vertex is outside the window boundary and the second vertex is inside
the window, then the intersection point with the boundary edge of window and vertex which
is inside the window is stored in a output vertex list.
Case 2: If both, first and second vertexes of a polygon are lying inside the window, and then
we have to store the second vertex only in output vertex list.
Case 3: If the first vertex is inside the window and second vertex is outside the window then
we have to store only intersection point of that edge of polygon with window in output vertex
list.
Case 4: If both the vertex first and second vertex of a polygon is lying outside the window
then no vertex is stored in output vertex list.
Algorithm:

Program:
// Sutherland Hodgeman Polygon Clipping
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>
void clip(float,float,float);
int i,j=0,n; int
rx1,rx2,ry1,ry2;
float x1[8],y1[8];
void main()
{
int gd=DETECT,gm;
int i,n; float
x[8],y[8],m;
clrscr();
initgraph(&gd,&gm,"c:\\turboc3\\bgi"); printf("coordinates
for rectangle : ");
scanf("%d%d%d%d",&rx1,&ry1,&rx2,&ry2);
printf("no. of sides for polygon : ");
scanf("%d",&n); printf("coordinates
: ");
for(i=0;i<n;i++)
{
scanf("%f%f",&x[i],&y[i]);
}
cleardevice();
outtextxy(10,10,"Before clipping");
outtextxy(10,470,"Press any key. ..
"); rectangle(rx1,ry1,rx2,ry2);
for(i=0;i<n-1;i++)
line(x[i],y[i],x[i+1],y[i+1]);
line(x[i],y[i],x[0],y[0]); getch();
cleardevice();
for(i=0;i<n-1;i++)
{
m=(y[i+1]-y[i])/(x[i+1]-x[i]);
clip(x[i],y[i],m); clip(x[i+1],y[i+1],m);
}
m=(y[i]-y[0])/(x[i]-x[0]);
clip(x[i],y[i],m); clip(x[0],y[0],m);
outtextxy(10,10,"After clipping");
outtextxy(10,470,"Press any key. ..
"); rectangle(rx1,ry1,rx2,ry2);
for(i=0;i<j-1;i++)
line(x1[i],y1[i],x1[i+1],y1[i+1]);
getch();
}

void clip(float e,float f,float m)


{
while(e<rx1||e>rx2||f<ry1||f>ry2)
{
if(e<rx1)
{
f+=m*(rx1-e);
e=rx1;
}
else if(e>rx2)
{
f+=m*(rx2-e);
e=rx2;
}
if(f<ry1)
{
e+=(ry1-f)/m;
f=ry1;
}
else if(f>ry2)
{
e+=(ry2-f)/m;
f=ry2;
}
}
x1[j]=e;
y1[j]=f;
j++;
}

You might also like