COMPUTER GRAPHICS NOTES CHAWATAMA T
The electron Gun
The electron gun fires electron which eventually strike the phosphors. The
electron gun consists of two main components, the cathode and the electron
beam focuser.
These two parts work together t fire an electron and help determine where it
will go.
The cathode
The cathode is made up of a metal conductor usually nickel.
Heat is supplied to the cathode by directing a current through a coil of wire,
called the filament inside the cathode.
This causes the electrons to be “boiled off” the hot cathode. In the vacuum
inside the CRT envelope, the free negatively charged electrons are then
accelerated towards the phosphor coating by a high positive voltage.
1
COMPUTER GRAPHICS NOTES CHAWATAMA T
The electron beam focuser
After an electron has been removed from the cathode and accelerated, it travels
through the electron beam focuser.
In most monitors and televisions, an electromagnetic mechanism can also be
used.
The focusing system in CRT is needed to force the electron beam to converge
into a small spot as it strikes the phosphor, otherwise the electrons would repel
each other, and the beam would spread out as it approaches the screen.
With electrostatic focusing, the electron beam passes through a positively
charged metal cylinder that forms an electrostatic lens.
The action of the electrostatic lens focuses the electron beam at the center of the
screen, in exactly the same way that an optical lens focuses a beam at a
particular focal lens.
The electron beam deflector
The electron beam deflector is positioned at the base of the vacuum tube and
controls what part of the screen the election strikes.
The electron beam deflector, like the focuser can rely on either an
electromagnetic or electrostatic mechanism.
The deflector determines the path of the electron. There are really two
deflectors, one that controls the position in the x or horizontal direction and one
in the y or vertical direction.
A current is run through the coil to control where the electron goes. The
electromagnetic force causes the electron to move towards either the left or the
right in the case of the horizontal deflector.
The deflector uses the force to change the path of the electron to determine
what part of the screen the electron hits, but not which phosphor.
2
COMPUTER GRAPHICS NOTES CHAWATAMA T
The Screen
The screen which is at the front of the CRT is what actually displays the image.
Sports of light are produced on the screen by the transfer of the CRT beam
energy to the phosphor.
When the electrons on the beam collide with the phosphor coating, they are
stopped and their kinetic energy is absorbed by the phosphor. Part of the beam
energy is converted by friction into heat energy and the remainder causes
electrons in the phosphor atoms to move up to higher quantum energy levels.
The excited electron then rises to a higher energy level. As the electron falls it
emits energy as heat and visible light.
Intensity
The intensity of the electron beam is controlled by setting voltage levels on the
control grid, which is a metal cylinder that fits over the cathode.
A high negative voltage applied to the control grid will shut off the beam by
repelling electrons and stopping them from passing through the small hole at
the end of the control grid structure.
A smaller negative voltage on the control grid simply decreases the number of
electrons passing through.
Since the amount of light emitted by the phosphor coating depends on the
number of electrons striking the screen, we control the brightness of a display
by varying the voltage on the control grid.
How a CRT monitor operates (summary)
The CRT operates by firing an electron beam at phosphors, which give off light.
The electron beam is generated at the cathode in the electron gun.
3
COMPUTER GRAPHICS NOTES CHAWATAMA T
A potential (voltage) is applied, which strips off and accelerates the electrons.
The electrons then travel to the to the electron beam focuser. An electrostatic
mechanism is used to focus the beam.
After the beam exits from the electron gun, it travels to the electron beam
deflector. The deflector has two mechanisms, one to change the vertical
direction and one to change the horizontal direction of the beam. This allows
the electron beam to sweep over the entire screen.
When an electron in the beam strikes a phosphor, it excites an electron in the
phosphor. After being excited, the electron then releases the energy it got in a
form of visible light, which is always the same for that phosphor.
Phosphors emitting red, blue, and green light form a color image. Figure below
shows the overall path of the electron beam. The electron beam is constantly
being created and focused.
CRT properties
Persistence
Different kinds of phosphors are available for use in CRT. Besides color, a
major difference between phosphors is their persistence – i.e. how long they
continue to emit light after the CRT beam is removed.
Persistence is defined as the time it takes the emitted light from the screen to
decay to one tenth to one-tenth of its original intensity.
Lower persistence phosphors require high refresh rates to maintain a picture on
the screen without flicker.
A phosphor with low persistence is useful for animation; a high persistence
phosphor is useful for displaying high complex, static pictures.
4
COMPUTER GRAPHICS NOTES CHAWATAMA T
Resolution
The maximum number of points (pixels) that can be displayed without overlap
on a CRT.
Monitors that display more pixels offer a sharper, brighter image, for e.g. a 640
by 480 pixel screen is capable of displaying 640 distinct dots on each of 480
lines or about 300 000 pixels.
The resolution of a CRT is dependent on the type of phosphor, the intensity to
be displayed and the focusing and deflection systems.
Typical resolution on high quality systems is 1280 by 1024, with higher
resolutions available on many systems.
Aspect Ratio
Another property of video monitors is the aspect ratio.
This number gives the ratio of vertical points to horizontal points necessary to
produce equal length lines in both directions on the screen.
The aspect ratio in most cases is stated as a ratio of horizontal to vertical points.
An aspect ratio of ¾ means that a vertical line plotted with three points has the
same length as a horizontal line plotted with four points.
Pixels
Each point on the screen is referred to as a pixel or pel (shortened forms of
picture elements).
In computer graphics, pictures or graphics objects are presented as a collection
of discrete picture elements called pixels. The pixel is the smallest addressable
screen element.
It is the smallest piece of the display screen which we can control. The control
is achieved by setting the intensity and color of the pixel which compose the
screen.
Each pixel on the graphics display does not represent mathematical point.
Rather, it represents a region which theoretically can contain an infinite number
of points.
For example, if we want to display point P₁ whose co-ordinates are (4.4,3.8) and
point P₂ whose co-ordinates are (4.7,3.3) then P₁ and P₂ are represented by only
one pixel (4,3), as shown in the figure below
5
COMPUTER GRAPHICS NOTES CHAWATAMA T
The special procedures determine which pixel will provide the best
approximation to the desired picture or graphics object.
The process of determining the appropriate pixels for representing picture or
graphics object is known as rasterization, and the process of representing
continuous picture or graphics object as a collection of discrete pixels is called
scan conversion.
Bitmap
A bitmap (or raster graphic) is a digital image composed of a matrix of dots.
When viewed at 100%, each dot corresponds to an individual pixel on a display.
In a standard bitmap, each dot can be assigned a different color.
Dot Pitch
The internal surface of monitor screen is coated with red, green, and blue
phosphor material that glows when struck by a stream of electrons.
This coated material is arranged into an area of tiny cells – red, green and blue
usually coated dots.
Dot pitch is the measurement of the diagonal distance between two like colored
(red, green or blue) pixels on a display screen.
6
COMPUTER GRAPHICS NOTES CHAWATAMA T
It is measured in mm. usually monitors are available with dot pitch specification
0.25mm to 0.40mm. The smaller the dot pitch, the higher the resolution,
sharpness and detail of image.
Refresh Rate
It is the number of times per second the pixels are recharged so that image does
not flicker.
Refresh rate for a monitor is measured in Hertz (Hz) which can also be called
frame rate, horizontal scan rate or vertical scan rate.
Normally refresh rate varies from 60 to 75Hz.a refresh rate of 60Hz means
image is redrawn 60 times a second. The higher the refresh rate, the lesser is the
flickering.
Flicker
The appearance of flickering, flashing or unsteadiness in an image may occur
on a display screen.
A flicker issue can occur when the video refresh rate is too low, other video
related issues and in some cases hardware issues with the monitor.
Frame Buffer
It is the refresh storage area in the digital memory, in which the matrix of
intensity values and parameters of all the pixels generating image are stored in
binary form.
The size of the frame buffer determines the resolution and maximum colors it is
able to display.
The frame buffer stores such information as brightness, and color values of the
corresponding pixel in the screen.
Raster Scan Display
7
COMPUTER GRAPHICS NOTES CHAWATAMA T
Raster scanning is a technique for generating or recording the elements of a
display image by sweeping the screen in a line-by-line manner.
More specifically, it scans the whole area, generally from left to right, while
progressing from top to bottom of the display monitor.
The lines that are scanned on the tube screen are produced by a narrow electron
beam that is focused into a small “spot” which is repeatedly moved across the
screen, then progressively down it until the entire area has been covered (that is
referred to as a raster).
The inside of the tube face is coated with a special phosphor that emits a bright
light when bombarded with electrons.
As the electron beam moves across each row, the beam intensity is turned on
and off to create a pattern of illuminated spots. The 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 screen points. Stored
intensity values are then retrieved from the refresh buffer and “painted” on the
screen one row (scan line) at a time.
Each screen point is referred to as a pixel. Refreshing on raster-scan displays is
carried out at the rate of 60 to 80 frames per second.
8
COMPUTER GRAPHICS NOTES CHAWATAMA T
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. The return to the left of the screen,
after refreshing each scan line is called horizontal retrace of the electron beam.
And at the end of each frame, the electron beam returns (vertical retrace) to the
top left corner of the screen to begin the next frame.
Interlacing
On some raster scan systems each frame is displayed in two passes using an
interlaced refresh procedure. In the first pass, the beam sweeps odd scan lines
across every other scan line from top to bottom.
Then after the vertical re-trace, the beam sweeps out the remaining even scan
lines. Interlacing of the scan lines in this way allows us to see the entire screen
displayed at once from top to bottom.
Interlacing is primarily used with slower refresh rates. This is an effective
technique for avoiding flicker, providing that adjacent scan lines contain similar
display information.
9
COMPUTER GRAPHICS NOTES CHAWATAMA T
Random Scan Display
In random scan display systems, the electron beam is directed to the particular
point of the screen where the image is to be drawn.
It generates the image by drawing set of straight lines in a similar way as the
pen plotting of an image on paper. This is why the technique is also referred to
as vector displays (or stroke writing/calligraphic display).
10
COMPUTER GRAPHICS NOTES CHAWATAMA T
The component lines of a picture can be drawn and refreshed by a random scan
system in any specified order.
In random scan system, 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.
After all line drawing commands have been processed, the system cycles back
to the first line command in the list.
Refresh rate on a random scan system depends on the number of lines to be
displayed. Random scan displays are designed to draw all component lines of a
picture 30 to 60 times each second.
Random scan displays are designed for line drawing applications and can’t
display realistic shaded scenes.
Since picture definition is stored as a set of line drawing instructions and not as
a set of intensity values for all screen points, vector displays generally have
higher resolution than raster systems.
Differences between Random Scan and Raster Scan display
Random Scan Display Raster Scan Display
In random scan display the beam is In raster scan displays the beam is
moved between the end points of the moved all over the screen one scan
graphic primitives. line at a time from top to bottom and
then back to top.
Picture definition is stored as a set of Picture definition is stored as a set of
line drawing instructions in a display intensity values for all screen points,
file. called pixels in a refresh buffer area.
Random scan display only draws Raster scan has the ability to display
lines and characters. areas filled with solid colors or
patterns.
It doesn’t use interlacing It uses interlacing
It has high resolution. It has less resolution.
Refresh rate depends directly on Refresh rate independent of picture
picture complexity complexity
Scan conversion is not required. Graphics primitives are specific in
terms of their endpoints and must be
11
COMPUTER GRAPHICS NOTES CHAWATAMA T
scan converted into their
corresponding pixels in the frame
buffer.
Mathematical functions are used to Screen points/pixels are used to draw
draw an image an image.
Color CRT Monitors
To display color pictures, combination of phosphors is used that emits different
colored light. There are two different techniques for producing color displays with
a CRT.
1. Beam Penetration Method
2. Shadow Mask Method
Beam Penetration 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.
12
COMPUTER GRAPHICS NOTES CHAWATAMA T
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.
However only four colors are possible, and the quality of pictures is not as good
as compared to other methods.
Beam penetration is an inexpensive way to produce color on random scan
monitors.
Shadow Mask Method
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 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 activate 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 dot when it passes through the shadow
mask.
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 from 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 on composite.
The color we see depends on the amount of excitation of the red, green and blue
phosphors. A white (gray) color is the result of activating all three dots with
equal intensity.
13
COMPUTER GRAPHICS NOTES CHAWATAMA T
The problem with shadow mask CRTs is that of convergence. It is extremely
difficult to adjust three guns and deflection systems so that electron beams are
deflected exactly together, all converging on the same hole in theshadow mask.
Direct-View Storage Tubes (DVST)
This is an alternative method to monitor a screen image, as it sores the picture
information inside the CRT instead of refreshing the screen.
A direct-view storage tube (DVST) stores the picture information as a charge
distribution just behind the phosphor-coated screen.
14
COMPUTER GRAPHICS NOTES CHAWATAMA T
Two electron guns are used in a DVST. One, the primary gun, is used to store
the picture pattern; the second, the flood gun, maintains the picture display.
A DVST monitor has both disadvantages and advantages compared to the
refresh CRT. Because no refreshing is needed, very complex pictures can be
displayed at very high resolutions without flicker.
Disadvantages of DVST systems are that they ordinarily do not display color
and that selected parts of a picture cannot be erased.
To eliminate a picture section, the entire screen must be erased and the
modified picture redrawn.
The erasing and redrawing process can take several seconds for a complex
picture. For these reasons, storage displays have been largely replaced by raster
systems.
Flat-Panel Displays
The term flat panel display refers to a class of video device that have reduced
volume, weight and power requirement compared to a CRT.
A significant feature of flat-panel displays is that they are thinner than CRTs,
and we can hang them on walls or wear them on our wrists.
Current uses for flat-panel displays include small TV monitors, calculators,
pocket video games, laptop computers, armrest viewing of movies on airlines,
as advertisement boards in elevators, and as graphics displays in applications
requiring rugged, portable monitors.
We can separate flat-panel displays into two categories: emissive displays and
nonemissive displays. The emissive displays (or emitters) are devices that
convert electrical energy into light.
Plasma panels, thin-film electroluminescent displays, and- light-emitting
diodes are examples of emissive displays.
Flat CRTs have also been devised, in which electron beams are accelerated
parallel to the screen, then deflected 90° to the screen. But flat CRTs have not
proved to be as successful as other emissive devices.
Nonemmissive displays (or nonemitters) use optical effects to convert sunlight
or light from some other source into graphics patterns.
The most important example of a nonemissive flat-panel display is a liquid-
crystal device.
15
COMPUTER GRAPHICS NOTES CHAWATAMA T
Liquid-crystal Displays (LCDs)
Liquid crystal displays are the devices that produce a picture by passing
polarized light from the surroundings or from an internal light source through a
liquid crystal material that transmit the light.
Liquid-crystal displays (LCDs) are commonly used in small systems, such ' as
calculators and portable, laptop computers.
These non-emissive devices produce a picture by passing polarized light from
the surroundings or from an internal light source through a liquid-crystal
material that can be aligned to either block or transmit the light.
The term liquid crystal refers to the fact that these compounds have a crystalline
arrangement of molecules, yet they flow like a liquid. Flat-panel displays
commonly use nematic (threadlike) liquid-crystal compounds that tend to keep
the long axes of the rod-shaped molecules aligned.
A flat-panel display can then be constructed with a nematic liquid crystal, as
demonstrated in Fig below. Two glass plates, each containing a light polarizer
at right angles to the other plate, sandwich the liquid-crystal material.
Rows of horizontal transparent conductors are built into one glass plate, and
columns of vertical conductors are put into the other plate. The intersection of
two conductors defines a pixel position.
Normally, the molecules are aligned as shown in the "on state" of Fig below.
Polarized light passing through the material is twisted so that it will pass
through the opposite polarizer.
The light is then reflected back to the viewer. To turn off the pixel, we apply a
voltage to the two intersecting conductors to align the molecules so that the
light is not twisted.
This type of flat-panel device is referred to as a passive-matrix LCD. Picture
definitions are stored in a refresh buffer, and the screen is refreshed at the rate
of 60 frames per second, as in the emissive devices.
Back lighting is also commonly applied using solid-state electronic devices, so
that the system is not completely dependent on outside light sources.
Colors can be displayed by using different materials or dyes and by placing a
triad of color pixels at each screen location. Another method for constructing
LCDs is to place a transistor at each pixel location, using thin-film transistor
technology.
The transistors are used to control the voltage at pixel locations and to prevent
charge from gradually leaking out of the liquid-crystal cells. These devices are
called active-matrix displays.
16
COMPUTER GRAPHICS NOTES CHAWATAMA T
17
COMPUTER GRAPHICS NOTES CHAWATAMA T
Scan conversion
The process of representing continuously graphic objects as a collection of
discrete pixels is called scan conversion (rasterization).
In other words, we can say that scan conversion is continuous to discrete
transformation. Shapes and colors of the object can be described internally with
pixel arrays or with sets of basic geometric structures such as straight line
segments and polygon color areas.
The scene is then displayed either by loading the pixel areas into the frame
buffer or by scan converting the basic geometric structure specifications into
pixel pattern.
Line Drawing
Line drawing is accomplished by calculating intermediate positions along the
line path between two specified end positions.
An output device is then directed to fill in these positions between the endpoints
positions. For analogue devices, such as a vector pen plotter or a random scan
display, a straight line can be drawn smoothly from one end point to the other.
Linearly varying horizontal and vertical deflection voltages are generated that
are proportional to the required changes in the x and y direction to produce the
smooth line.
Digital devices display a straight line segment by plotting discrete points
between the two end points. Discrete coordinate positions along the line path
are calculated from the equation of the line.
For a raster video display, the line color (intensity) is then loaded into the frame
buffer at the corresponding pixel coordinates.
Reading from the frame buffer, the video controller then “plots” the screen
pixels. Screen locations are referenced with integer values, so plotted positions
may only approximate actual line positions between two specified endpoints.
A computed line position of (10.48, 20.51) for example would be converted to
pixel position (10, 21).
18
COMPUTER GRAPHICS NOTES CHAWATAMA T
Scan conversion of lines
Characteristics of a good line drawing algorithm
1. It draws lines that appear straight.
2. It draws lines that have constant density.
3. It draws lines rapidly
4. The lines drawn should start and terminate accurately.
19
COMPUTER GRAPHICS NOTES CHAWATAMA T
20
COMPUTER GRAPHICS NOTES CHAWATAMA T
21
COMPUTER GRAPHICS NOTES CHAWATAMA T
22
COMPUTER GRAPHICS NOTES CHAWATAMA T
23
COMPUTER GRAPHICS NOTES CHAWATAMA T
24
COMPUTER GRAPHICS NOTES CHAWATAMA T
25
COMPUTER GRAPHICS NOTES CHAWATAMA T
Program to implement DDA Line Drawing Algorithm
#include<iostream.h>
#include<graphics.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
#include<stdlib.h>
#include<stdio.h>
class lines
{
private:
int length,x1,y1,x2,y2,x,y,dx,dy,wx,wy,w,width;
public:
lines(); //Constructor
void showline();
int sign(int);
};
int lines::sign(int xx)
{
if(xx<0)
return -1;
if(xx==0)
26
COMPUTER GRAPHICS NOTES CHAWATAMA T
return 0;
if(xx>0)
return 1;
return 0;
}
lines::lines()
{
x=0;y=0;
cout<<"
"Enter The Co-Ordinates (x1,y1) ":=";
cin>>x1>>y1;
cout<<"
"Enter The Co-Ordinates (x2,y2) ":=";
cin>>x2>>y2;
cout<<"
"Enter The Width Of The Line ":=";
cin>>width;
}
void lines::showline()
{
char *s,*s1;
if(abs(x2-x1)>=abs(y2-y1))
length=abs(x2-x1);
else
length=abs(y2-y1);
w=width;
wx=((w-1)/2)*(sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))/abs(y2-y1));
wy=((w-1)/2)*(sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))/abs(x2-x1));
dx=(x2-x1)/length;
dy=(y2-y1)/length;
if(dy>dx)
wy=wx;
x=x1+0.5*sign(dx);
y=y1+0.5*sign(dy);
27
COMPUTER GRAPHICS NOTES CHAWATAMA T
int i=1;
setcolor(0);
while(i<=length)
{
for(int j=0;j<wy;j++)
putpixel((x+320),480-(y+240+j),6);
for(j=0;j<wy;j++)
putpixel((x+320),480-(y+240-j),6);
putpixel((x+320),480-(y+240),6);
x+=dx;
y+=dy;
i++;
}
setcolor(15);
outtextxy(40,10,"The Points Are:=");
sprintf(s,"A(%d,%d)",x1,y1);
outtextxy(40,20,s);
sprintf(s,"B(%d,%d)",x2,y2);
outtextxy(40,30,s);
getch();
}
void main()
{
int gd=DETECT,gm,i,j,xx=240,xxx=380;
clrscr();
lines a;
char *mess[]={"D","D","A"," ","A","L","G","O","R","I","T","H","M"};
initgraph(&gd,&gm,"..\bgi");
cleardevice();
rectangle(120,40,320,240);
rectangle(320,40,520,240);
rectangle(120,240,320,440);
rectangle(320,240,520,440);
for(i=0,j=12;i<8,j>=6;i++,j--)
{
28
COMPUTER GRAPHICS NOTES CHAWATAMA T
xx+=10;
outtextxy(xx,10,mess[i]);
xxx-=10;
outtextxy(xxx,10,mess[j]);
delay(100);
}
for(i=130;i<=510;i+=10)
for(j=50;j<=430;j+=10)
putpixel(i,j,15);
for(i=130;i<=510;i+=10)
{
if(i==320)
continue;
outtextxy(i,237,"+");
}
for(i=50;i<=430;i+=10)
{
if(i==240)
continue;
outtextxy(317,i,"-");
}
outtextxy(310,230,"O");
outtextxy(530,240,"X");
outtextxy(320,450,"-Y");
outtextxy(100,240,"-X");
outtextxy(320,30,"Y");
[Link]();
closegraph();
}
29
COMPUTER GRAPHICS NOTES CHAWATAMA T
Bresenham’s Line Algorithm
Bresenham’s line algorithm uses only integer addition and subtraction and multiplication by
2.
The basic principle of Bresenham’s line algorithm is to select the optimum raster locations to
represent a straight line. To accomplish this, the algorithm always increment either x or y by
one unit depending on the slope of line.
The increment in the other variable is determined by examining the distance between the
actual line location and the nearest pixel. The distance is called decision variable or the error.
This is illustrated in the diagram below. As shown in the diagram below, the line does not
pass through all raster points (pixels). It passes through raster point (0, 0) and subsequently
crosses three pixels. It is seen that the intercept of line with the line = 1 is closer to the line
y=0, i.e. pixel (1,0) than to the line y=1 i.e. pixel (1,1). Hence in this case the raster point at
(1, 0) better represents the path of the line than at (1,1). The intercept of the line with the line
x=2 is close to the line y=1, i.e. pixel (2, 1) than to the line y=0, i.e. pixel (2,0). Hence, the
raster point at (2,1) better represents the path of the line as shown in the diagram.
In mathematical terms error or decision variable is defined as
E = DB – DA 0r DA - DB
30
COMPUTER GRAPHICS NOTES CHAWATAMA T
C++ IMPLEMENTATION OF BRESENHAM ALGORITHM
# include <iostream.h>
# include <conio.h>
# include <graphics.h>
# include <math.h>
char IncFlag;
void Bresenham(int x1,int x2,int y1,int y2);
void DrawLine(int X,int Y,int End,int PInc,int NInc,int P,int XInc,int YInc);
void main()
{
int gDriver=DETECT, gMode;
int x1,x2,y1,y2;
void Bresenham(int,int,int,int);
initgraph(&gDriver,&gMode,"c:\\tc\\bgi");
cout<<endl<<"x1 : ";
cin>>x1;
cout<<endl<<"y1 : ";
cin>>y1;
31
COMPUTER GRAPHICS NOTES CHAWATAMA T
cout<<endl<<"x2 : ";
cin>>x2;
cout<<endl<<"y2 : ";
cin>>y2;
line(320,0,320,480);
line(0,240,640,240);
Bresenham(x1,x2,y1,y2);
getch();
}
void Bresenham(int x1,int x2,int y1,int y2)
{
int S,O,End;
int P;
int dx = abs(x1 - x2);
int dy = abs(y1 - y2);
float Slope;
int PInc,NInc,XInc,YInc;
if (dx == 0) //Slope Infinite
{
}
else
{
Slope = (float)(y1 - y2) / (x1 - x2);
if (Slope>-1 && Slope<1)
{
IncFlag = 'X';
PInc = 2 * (dy - dx);
NInc = 2 * dy;
P = 2 * dy - dx;
if (x1>x2)
{
S = x2;
O = y2;
End = x1;
}
else
{
S = x1;
O = y1;
End = x2;
}
// DrawLine(x,y,End,PInc,NInc,P,XInc,YInc);
}
else
{
IncFlag = 'Y';
PInc = 2 * (dx - dy);
NInc = 2 * dx;
P = 2 * dx - dy;
if (y1 > y2)
{
O = x2;
S = y2;
End = y1;
}
else
{
O = x1;
S = y1;
End = y2;
}
32
COMPUTER GRAPHICS NOTES CHAWATAMA T
}
if (IncFlag == 'X')
putpixel(320+S,240-O,12);
else
putpixel(320+O,240-S,12);
while (S <= End)
{
S++;
if (P<0)
P = P + NInc;
else
{
P = P + PInc;
if (Slope>0.0)
O++;
else
O--;
}
if (IncFlag == 'X')
putpixel(320+S,240-O,12);
else
putpixel(320+O,240-S,12);
}
}
}
33
COMPUTER GRAPHICS NOTES CHAWATAMA T
34
COMPUTER GRAPHICS NOTES CHAWATAMA T
35
COMPUTER GRAPHICS NOTES CHAWATAMA T
36
COMPUTER GRAPHICS NOTES CHAWATAMA T
Clipping
Typically a graphics package allows us to specify which part of a defined is to be displayed and
where that part is to be displayed on the display device. Furthermore, the package also provides the
use of the scaling, translation and rotation techniques to generate a variety of different views of a
single picture.
We can generate different views of a picture by applying the appropriate scaling and translation.
While doing this, we have to identify the visible part of the picture for inclusion in the display image.
This selection process is not straight forward. Certain lines may lie partly inside the visible portion of
the picture and partly outside. These lines cannot be omitted entirely from the display image because
the image would become inaccurate.
The process of selecting and viewing the picture with different views is called windowing and a
process which divides each element of the picture into its visible and invisible portions, allowing the
invisible portion to be discarded is called clipping.
37
COMPUTER GRAPHICS NOTES CHAWATAMA T
The region against which an object is to be clipped is called a clip window or clipping window. It
usually is in a rectangular shape.
The clipping algorithm determines which points, lines or portions of lines within the clipping
window. These points, lines or portions of lines are retained for display. All others are discarded.
38
COMPUTER GRAPHICS NOTES CHAWATAMA T
39
COMPUTER GRAPHICS NOTES CHAWATAMA T
40
COMPUTER GRAPHICS NOTES CHAWATAMA T
41
COMPUTER GRAPHICS NOTES CHAWATAMA T
42
COMPUTER GRAPHICS NOTES CHAWATAMA T
43
COMPUTER GRAPHICS NOTES CHAWATAMA T
C++ IMPLEMENTATION OF COHEN SUNDERLAND ALGORITHM
#include <iostream.h>
#include <graphics.h>
#include <stdio.h>
#include <conio.h>
FILE *fp;
class clipping
{
private:
int x;
int y;
int code[4];
public:
clipping();
void getxy(char p[5]);
void encode(int left,int right,int bottom,int top);
int getcode(int k);
float getx(void);
float gety(void);
44
COMPUTER GRAPHICS NOTES CHAWATAMA T
friend int accept(clipping p1,clipping p2);
friend int reject(clipping p1,clipping p2);
friend void swap_points(clipping &p1,clipping &p2);
int point_inside(void);
void clipping::operator =(clipping p2);
void changex(int winy,float m);
void changey(int winx,float m);
};
clipping::clipping()
{
int i;
x = 0;
y = 0;
for(i=0;i<4;i++)
code[i] = 0;
}
float clipping::getx(void)
{
return(x);
}
float clipping::gety(void)
{
return(y);
}
void clipping::getxy(char p[5])
{
cout << "\nEnter the coordinates of point " << p;
cout << "\nX :- ";
fscanf(fp,"%d",&x);
cout << "\nY :- ";
fscanf(fp,"%d",&y);
}
void clipping::encode(int left,int right,int bottom,int top)
{
if(x < left)
code[0] = 1;
else
code[0] = 0;
if (x > right)
code[1] = 1;
else
code[1] = 0;
if (y > bottom)
code[2] = 1;
else
code[2] = 0;
if (y < top)
code[3] = 1;
else
code[3] = 0;
}
int clipping::getcode(int k)
{
if (code[k] == 1)
return(1);
return(0);
45
COMPUTER GRAPHICS NOTES CHAWATAMA T
int accept(clipping p1,clipping p2)
{
int k;
for(k=0;k<4;k++)
if ([Link](k) || [Link](k))
return(0);
return(1);
}
int reject(clipping p1,clipping p2)
{
int k;
for(k=0;k<4;k++)
if ([Link](k) && [Link](k))
return(1);
return(0);
}
int clipping::point_inside(void)
{
if (code[0] || code[1] || code[2] || code[3])
return(0);
return(1);
}
void clipping::operator =(clipping p2)
{
int i;
x = p2.x;
y = p2.y;
for (i=0;i<4;i++)
code[i] = [Link][i];
}
void swap_points(clipping &p1,clipping &p2)
{
clipping tmp;
tmp = p1;
p1 = p2;
p2 = tmp;
}
void clipping::changex(int winy,float m)
{
x = x + (winy - y) / m;
y = winy;
}
void clipping::changey(int winx,float m)
{
y = y + (winx - x) * m;
x = winx;
}
void main()
{
int driver = DETECT,mode;
initgraph(&driver,&mode,"c:\\tc\\bgi");
clipping p1,p2,tmp;
int left,top,right,bottom,done=0,draw=0;
46
COMPUTER GRAPHICS NOTES CHAWATAMA T
float m;
fp = fopen("[Link]","r");
clearviewport();
[Link]("p1");
[Link]("p2");
left = getmaxx() / 2 - 50;
right = getmaxx() / 2 + 50;
bottom = getmaxy() / 2 + 50;
top = getmaxy() / 2 - 50;
clearviewport();
rectangle(left,top,right,bottom);
line([Link](),[Link](),[Link](),[Link]());
while(done == 0)
{
[Link](left,right,bottom,top);
[Link](left,right,bottom,top);
if (accept(p1,p2))
{
done = 1;
draw = 1;
}
elseif (reject(p1,p2))
{
done = 1;
}
else
{
if (p1.point_inside())
swap_points(p1,p2);
m = ([Link]() - [Link]()) / ([Link]() - [Link]());
if([Link](0))
[Link](left,m);
elseif([Link](1))
[Link](right,m);
elseif ([Link](2))
[Link](bottom,m);
elseif ([Link](3))
[Link](top,m);
}
cout << "\nPress any key to continue...\n";
getch();
clearviewport();
rectangle(left,top,right,bottom);
line([Link](),[Link](),[Link](),[Link]());
}
if (draw)
{
rectangle(left,top,right,bottom);
line([Link](),[Link](),[Link](),[Link]());
}
getch
47