CMP461 Computer Graphics and Animations 2nd Note
CMP461 Computer Graphics and Animations 2nd Note
COURSE TITLE:
COURSE CODE:
CMP 461
5. Recommended Textbooks
a. Jonas G., Luiz V., Mario C. S. (2018). Computer Graphics, Theory and Practice.
b. Alexey B., Evgeniy S. (2013). Computer Graphics, from Pixels to Programmable
Graphics Hardware
c. Garth Gardner, (2002). Computer Graphics and Animation: History, Careers and Expert
Advice
d. Malay K. Pakhira, (2010). Computer Graphics, Multimedia and Animation
e. Keith Osborn, (2015). Cartoon Character Animation with Maya
The aim of this course is to provide an introduction to the theory and practice of computer
graphics. By introducing topics that deal with computer graphics rendering of
primitive objects, polygon clipping algorithms, two-dimensional transformations, three-
dimensional transformations, viewing camera rendering and projections, object representations,
three-dimensional curve and surface were rendering algorithms, and line and surface removal
algorithms.
In order to achieve the laid down goals, the course has a set of objectives. Each
unit is designed with specific objectives at the beginning. The students are advised
to read these objectives very carefully before embarking on the study unit. You may also
wish to refer to them during your study in order to measure your progress. You are also advised
to look at the unit objectives after completion of each unit. By so doing, you would have
followed the instruction of the unit. Below are the comprehensive listings of the overall
objective s of the course. By meeting these objectives, the said aims of the course must have
been achieved. Thus the after going through this course you should be able to:
Explain the overall workflow and techniques involved in computer animation
production.
To understand the fundamental computer graphics topics including graphics pipeline
architecture, transformations, modeling, viewing, shading, and texture mapping.
To study basic mathematical backgrounds related to computer graphics
including linear algebra and geometry.
Understand vividly, those computer graphic algorithms (such as object
transformation, geometric representation, shading and illumination model, anti-
aliasing and Ray tracing).
Study 3-D curve and surface algorithms, in rendering, surface and line removal
algorithms
Explain the abstract mathematical model describing the way color scan be represented
Understand the methods of Computing a digital image of what the virtual camera sees
8. Course Outline
9. Assessment method
It is difficult to display an image of any size on the computer screen. This method is simplified
by using Computer graphics. Graphics on the computer are produced by using various algorithms
and techniques. This tutorial describes how a rich visual experience is provided to the user by
explaining how all these processed by the computer.
Computer Graphics involves technology to access. The Process transforms and presents
information in a visual form. In today life, computer graphics has now become a common
element in user interfaces, T.V. commercial motion pictures.
Computer Graphics is the creation of pictures with the help of a computer. The end product of
the computer graphics is a picture it may be a business graph, drawing, and engineering.
In computer graphics, two or three-dimensional pictures can be created that are used for research.
Many hardware devices algorithm has been developing for improving the speed of picture
generation with the passes of time. It includes the creation storage of models and image of
objects. These models for various fields like engineering, mathematical and so on.
Today computer graphics is entirely different from the earlier one. It is not possible. It is an
interactive user can control the structure of an object of various input devices.
It is the use of computers to create and manipulate pictures on a display device. It comprises of
software techniques to create, store, modify, represents pictures.
Suppose a shoe manufacturing company want to show the sale of shoes for five years. For this
vast amount of information is to store. So a lot of time and memory will be needed. This method
will be tough to understand by a common man. In this situation graphics is a better alternative.
Graphics tools are charts and graphs. Using graphs, data can be represented in pictorial form. A
picture can be understood easily just with a single look.
Interactive computer graphics work using the concept of two-way communication between
computer users. The computer will receive signals from the input device, and the picture is
modified accordingly. Picture will be changed quickly when we apply command.
Application of Computer Graphics
For some training applications, particular systems are designed. For example Flight Simulator.
Flight Simulator: It helps in giving training to the pilots of airplanes. These pilots spend much
of their training not in a real aircraft but on the ground at the controls of a Flight Simulator.
Advantages:
1. Fuel Saving
2. Safety
3. Ability to familiarize the training with a large number of the world's airports.
2. Use in Biology: Molecular biologist can display a picture of molecules and gain insight into
their structure with the help of computer graphics.
5. Presentation Graphics: Example of presentation Graphics are bar charts, line graphs, pie
charts and other displays showing relationships between multiple parameters. Presentation
Graphics is commonly used to summarize
o Financial Reports
o Statistical Reports
o Mathematical Reports
o Scientific Reports
o Managerial Reports
6. Computer Art: Computer Graphics are also used in the field of commercial arts. It is used to
generate television and advertising commercial.
7. Entertainment: Computer Graphics are now commonly used in making motion pictures,
music videos and television shows.
10. Printing Technology: Computer Graphics is used for printing technology and textile design.
1. LOGO
2. COREL DRAW
3. AUTO CAD
4. 3D STUDIO
5. CORE
7. PHIGS
In non-interactive computer graphics, the picture is produced on the monitor, and the user does
not have any controlled over the image, i.e., the user cannot make any change in the rendered
image. One example of its Titles shown on T.V.
Non-interactive Graphics involves only one-way communication between the computer and the
user, User can see the produced image, and he cannot make any change in the image.
In interactive Computer Graphics user have some controls over the picture, i.e., the user can
make any change in the produced image. One example of it is the ping-pong game.
Interactive Computer Graphics require two-way communication between the computer and the
user. A User can see the image and make any change by sending his command with an input
device.
Advantages:
1. Higher Quality
3. Greater Productivity
The modern graphics display is very simple in construction. It consists of three components:
2. A Monitor likes a home T.V. set without the tuning and receiving electronics.
3. Display Controller or Video Controller: It passes the contents of the frame buffer to
the monitor.
Frame Buffer: A digital frame buffer is large, contiguous piece of computer memory used to
hold or map the image displayed on the screen.
o At a minimum, there is 1 memory bit for each pixel in the raster. This amount of memory
is called a bit plane.
o ∵ A memory bit has only two states (binary 0 or 1), a single bit plane yields a black and
white (monochrome display).
2. Resolution: Use to describe the number of pixels that are used on display image.
3. Aspect Ratio: It is the ratio of width to its height. Its measure is unit in length or number of
pixels.
Aspect Ratio =
Graphics Systems
Display Processor:
It is interpreter or piece of hardware that converts display processor code into pictures. It is one
of the four main parts of the display processor
2. Display Processor
3. Display Generator
4. Display Console
Display File Memory: It is used for generation of the picture. It is used for identification of
graphic entities.
Display Controller:
1. It handles interrupt
2. It maintains timings
Display Generator:
Display Console: It contains CRT, Light Pen, and Keyboard and deflection system.
The raster scan system is a combination of some processing units. It consists of the control
processing unit (CPU) and a particular processor called a display controller. Display Controller
controls the operation of the display device. It is also called a video controller.
Working: The video controller in the output circuitry generates the horizontal and vertical drive
signals so that the monitor can sweep. Its beam across the screen during raster scans.
As fig showing that 2 registers (X register and Y register) are used to store the coordinate of the
screen pixels. Assume that y values of the adjacent scan lines increased by 1 in an upward
direction starting from 0 at the bottom of the screen to ymax at the top and along each scan line the
screen pixel positions or x values are incremented by 1 from 0 at the leftmost position to xmax at
the rightmost position.
The origin is at the lowest left corner of the screen as in a standard Cartesian coordinate system.
At the start of a Refresh Cycle:
X register is set to 0 and y register is set to ymax. This (x, y') address is translated into a memory
address of frame buffer where the color value for this pixel position is stored.
The controller receives this color value (a binary no) from the frame buffer, breaks it up into
three parts and sends each element to a separate Digital-to-Analog Converter (DAC).
These voltages, in turn, controls the intensity of 3 e-beam that are focused at the (x, y) screen
position by the horizontal and vertical drive signals.
This process is repeated for each pixel along the top scan line, each time incrementing the X
register by Y.
As pixels on the first scan line are generated, the X register is incremented throughxmax.
Then x register is reset to 0, and y register is decremented by 1 to access the next scan line.
Pixel along each scan line is then processed, and the procedure is repeated for each successive
scan line units pixels on the last scan line (y=0) are generated.
For a display system employing a color look-up table frame buffer value is not directly used to
control the CRT beam intensity.
It is used as an index to find the three pixel-color value from the look-up table. This lookup
operation is done for each pixel on every display cycle.
As the time available to display or refresh a single pixel in the screen is too less, accessing the
frame buffer every time for reading each pixel intensity value would consume more time what is
allowed:
Multiple adjacent pixel values are fetched to the frame buffer in single access and stored in the
register.
After every allowable time gap, the one-pixel value is shifted out from the register to control the
warm intensity for that pixel.
The procedure is repeated with the next block of pixels, and so on, thus the whole group of pixels
will be processed.
Display Devices:
The most commonly used display device is a video monitor. The operation of most video
monitors based on CRT (Cathode Ray Tube). The following display devices are used:
6. Lookup Table
CRT stands for Cathode Ray Tube. CRT is a technology used in traditional computer monitors
and televisions. The image on CRT display is created by firing electrons from the back of the
tube of phosphorus located towards the front of the screen.
Once the electron heats the phosphorus, they light up, and they are projected on a screen. The
color you view on the screen is produced by a blend of red, blue and green light.
Components of CRT:
3. Focusing system: It is used to create a clear picture by focusing the electrons into a narrow
beam.
4. Deflection Yoke: It is used to control the direction of the electron beam. It creates an electric
or magnetic field which will bend the electron beam as it passes through the area. In a
conventional CRT, the yoke is linked to a sweep or scan generator. The deflection yoke which is
connected to the sweep generator creates a fluctuating electric or magnetic potential.
5. Phosphorus-coated screen: The inside front surface of every CRT is coated with phosphors.
Phosphors glow when a high-energy electron beam hits them. Phosphorescence is the term used
to characterize the light given off by a phosphor after it has been exposed to an electron beam.
Random Scan System uses an electron beam which operates like a pencil to create a line image
on the CRT screen. The picture is constructed out of a sequence of straight-line segments. Each
line segment is drawn on the screen by directing the beam to move from one point on the screen
to the next, where its x & y coordinates define each point. After drawing the picture. The system
cycles back to the first line and design all the lines of the image 30 to 60 time each second. The
process is shown in fig:
Advantages:
1. A CRT has the electron beam directed only to the parts of the screen where an image is to
be drawn.
3. High Resolution
Disadvantages:
A Raster Scan Display is based on intensity control of pixels in the form of a rectangular box
called Raster on the screen. Information of on and off pixels is stored in refresh buffer or Frame
buffer. Televisions in our house are based on Raster Scan Method. The raster scan system can
store information of each pixel position, so it is suitable for realistic display of objects. Raster
Scan provides a refresh rate of 60 to 80 frames per second.
Frame Buffer is also known as Raster or bit map. In Frame Buffer the positions are called picture
elements or pixels. Beam refreshing is of two types. First is horizontal retracing and second is
vertical retracing. When the beam starts from the top left corner and reaches the bottom right
scale, it will again return to the top left side called at vertical retrace. Then it will again more
horizontally from top to bottom call as horizontal retracing shown in fig:
1. Interlaced Scanning
2. Non-Interlaced Scanning
In Interlaced scanning, each horizontal line of the screen is traced from top to bottom. Due to
which fading of display of object may occur. This problem can be solved by Non-Interlaced
scanning. In this first of all odd numbered lines are traced or visited by an electron beam, then in
the next circle, even number of lines are located.
For non-interlaced display refresh rate of 30 frames per second used. But it gives flickers. For
interlaced display refresh rate of 60 frames per second is used.
Advantages:
1. Realistic image
Disadvantages:
1. Low Resolution
2. Expensive
5. Refresh rate depends or resolution 5. Refresh rate does not depend on the picture.
7. Beam Penetration technology come under it. 7. Shadow mark technology came under this.
The CRT Monitor display by using a combination of phosphors. The phosphors are different
colors. There are two popular approaches for producing color displays with a CRT are:
2. Shadow-Mask Method
The Beam-Penetration method has been used with random-scan monitors. In this method, the
CRT screen is coated with two layers of phosphor, red and green and the displayed color
depends on how far the electron beam penetrates the phosphor layers. This method produces four
colors only, red, green, orange and yellow. A beam of slow electrons excites the outer red layer
only; hence screen shows red color only. A beam of high-speed electrons excites the inner green
layer. Thus screen shows a green color.
Advantages:
1. Inexpensive
Disadvantages:
2. Shadow-Mask Method:
o Shadow Mask Method is commonly used in Raster-Scan System because they produce a
much wider range of colors than the beam-penetration method.
Construction: A shadow mask CRT has 3 phosphor color dots at each pixel position.
This type of CRT has 3 electron guns, one for each color dot and a shadow mask grid just behind
the phosphor coated screen.
Shadow mask grid is pierced with small round holes in a triangular pattern.
Figure shows the delta-delta shadow mask method commonly used in color CRT system.
Working: Triad arrangement of red, green, and blue guns.
The deflection system of the CRT operates on all 3 electron beams simultaneously; the 3 electron
beams are deflected and focused as a group onto the shadow mask, which contains a sequence of
holes aligned with the phosphor- dot patterns.
When the three beams pass through a hole in the shadow mask, they activate a dotted triangle,
which occurs as a small color spot on the screen.
The phosphor dots in the triangles are organized so that each electron beam can activate only its
corresponding color dot when it passes through the shadow mask.
electron guns and the corresponding red-green-blue color dots on the screen, are aligned along
one scan line rather of in a triangular pattern.
This inline arrangement of electron guns in easier to keep in alignment and is commonly used in
high-resolution color CRT's.
Advantage:
1. Realistic image
Disadvantage:
3. Convergence Problem
DVST terminals also use the random scan approach to generate the image on the CRT screen.
The term "storage tube" refers to the ability of the screen to retain the image which has been
projected against it, thus avoiding the need to rewrite the image constantly.
Function of guns: Two guns are used in DVST
Advantage:
1. No refreshing is needed.
2. High Resolution
Disadvantage:
The Flat-Panel display refers to a class of video devices that have reduced volume, weight and
power requirement compare to CRT.
Example: Small T.V. monitor, calculator, pocket video games, laptop computers, an
advertisement board in elevator.
1. Emissive Display: The emissive displays are devices that convert electrical energy into light.
Examples are Plasma Panel, thin film electroluminescent display and LED (Light Emitting
Diodes).
Plasma-Panels are also called as Gas-Discharge Display. It consists of an array of small lights.
Lights are fluorescent in nature. The essential components of the plasma-panel display are:
1. Cathode: It consists of fine wires. It delivers negative voltage to gas cells. The voltage is
released along with the negative axis.
2. Anode: It also consists of line wires. It delivers positive voltage. The voltage is supplied
along positive axis.
3. Fluorescent cells: It consists of small pockets of gas liquids when the voltage is applied
to this liquid (neon gas) it emits light.
4. Glass Plates: These plates act as capacitors. The voltage will be applied, the cell will
glow continuously.
The gas will slow when there is a significant voltage difference between horizontal and vertical
wires. The voltage level is kept between 90 volts to 120 volts. Plasma level does not require
refreshing. Erasing is done by reducing the voltage to 90 volts.
Each cell of plasma has two states, so cell is said to be stable. Displayable point in plasma panel
is made by the crossing of the horizontal and vertical grid. The resolution of the plasma panel
can be up to 512 * 512 pixels.
1. High Resolution
3. Less Volume
4. Less weight
Disadvantage:
1. Poor Resolution
In an LED, a matrix of diodes is organized to form the pixel positions in the display and picture
definition is stored in a refresh buffer. Data is read from the refresh buffer and converted to
voltage levels that are applied to the diodes to produce the light pattern in the display.
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 transmits the
light.
LCD uses the liquid-crystal material between two glass plates; each plate is the right angle to
each other between plates liquid is filled. One glass plate consists of rows of conductors arranged
in vertical direction. Another glass plate is consisting of a row of conductors arranged in
horizontal direction. The pixel position is determined by the intersection of the vertical &
horizontal conductor. This position is an active part of the screen.
Liquid crystal display is temperature dependent. It is between zero to seventy degree Celsius. It
is flat and requires very little power to operate.
Advantage:
3. Low Cost
Disadvantage:
2. LCDs do not emit light; as a result, the image has very little contrast.
Look-Up Table:
Image representation is essentially the description of pixel colors. There are three primary colors:
R (red), G (green) and B (blue). Each primary color can take on intensity levels produces a
variety of colors. Using direct coding, we may allocate 3 bits for each pixel, with one bit for each
primary color. The 3-bit representation allows each primary to vary independently between two
intensity levels: 0 (off) or 1 (on). Hence each pixel can take on one of the eight colors.
0 0 0 Black
0 0 1 Blue
0 1 0 Green
0 1 1 Cyan
1 0 0 Red
1 0 1 Magenta
1 1 0 Yellow
1 1 1 White
A widely accepted industry standard uses 3 bytes, or 24 bytes, per pixel, with one byte for each
primary color. The way, we allow each primary color to have 256 different intensity levels. Thus
a pixel can take on a color from 256 x 256 x 256 or 16.7 million possible choices. The 24-bit
format is commonly referred to as the actual color representation.
Lookup Table approach reduces the storage requirement. In this approach pixel values do not
code colors directly. Alternatively, they are addresses or indices into a table of color values. The
color of a particular pixel is determined by the color value in the table entry that the value of the
pixel references. Figure shows a look-up table with 256 entries. The entries have addresses 0
through 255. Each entry contains a 24-bit RGB color value. Pixel values are now 1-byte. The
color of a pixel whose value is i, where 0 <i<255, is persistence by the color value in the table
entry whose address is i. It reduces the storage requirement of a 1000 x 1000 image to one
million bytes plus 768 bytes for the color values in the look-up table.
INPUT/OUTPUT DEVICES
Input Devices
The Input Devices are the hardware that is used to transfer transfers input to the computer. The
data can be in the form of text, graphics, sound, and text. Output device display data from the
memory of the computer. Output can be text, numeric data, line, polygon, and other objects.
These Devices include:
1. Keyboard
2. Mouse
3. Trackball
4. Spaceball
5. Joystick
6. Light Pen
7. Digitizer
8. Touch Panels
9. Voice Recognition
Keyboard:
The most commonly used input device is a keyboard. The data is entered by pressing the set of
keys. All keys are labeled. A keyboard with 101 keys is called a QWERTY keyboard.
The keyboard has alphabetic as well as numeric keys. Some special keys are also available.
1. Numeric Keys: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
7. Numeric Keyboard: It is on the right-hand side of the keyboard and used for fast entry
of numeric data.
Function of Keyboard:
3. Special purpose keyboards are available having buttons, dials, and switches. Dials are
used to enter scalar values. Dials also enter real numbers. Buttons and switches are used
to enter predefined function values.
Advantage:
2. Function keys are a fast and effective method of using commands, with fewer errors.
Disadvantage:
Mouse:
A Mouse is a pointing device and used to position the pointer on the screen. It is a small palm
size box. There are two or three depression switches on the top. The movement of the mouse
along the x-axis helps in the horizontal movement of the cursor and the movement along the y-
axis helps in the vertical movement of the cursor on the screen. The mouse cannot be used to
enter text. Therefore, they are used in conjunction with a keyboard.
Advantage:
1. Easy to use
Advantage:
2. Compact Size
Spaceball:
It is similar to trackball, but it can move in six directions where trackball can move in two
directions only. The movement is recorded by the strain gauge. Strain gauge is applied with
pressure. It can be pushed and pulled in various directions. The ball has a diameter around 7.5
cm. The ball is mounted in the base using rollers. One-third of the ball is an inside box, the rest is
outside.
Applications:
Joystick:
A Joystick is also a pointing device which is used to change cursor position on a monitor screen.
Joystick is a stick having a spherical ball as its both lower and upper ends as shown in fig. The
lower spherical ball moves in a socket. The joystick can be changed in all four directions. The
function of a joystick is similar to that of the mouse. It is mainly used in Computer Aided
Designing (CAD) and playing computer games.
Light Pen
Light Pen (similar to the pen) is a pointing device which is used to select a displayed menu item
or draw pictures on the monitor screen. It consists of a photocell and an optical system placed in
a small tube. When its tip is moved over the monitor screen, and pen button is pressed, its
photocell sensing element detects the screen location and sends the corresponding signals to the
CPU.
Uses:
Digitizers:
The digitizer is an operator input device, which contains a large, smooth board (the appearance is
similar to the mechanical drawing board) & an electronic tracking device, which can be changed
over the surface to follow existing lines. The electronic tracking device contains a switch for the
user to record the desire x & y coordinate positions. The coordinates can be entered into the
computer memory or stored or an off-line storage medium such as magnetic tape.
Advantages:
Disadvantages:
1. Costly
Touch Panels:
Touch Panels is a type of display screen that has a touch-sensitive transparent panel covering the
screen. A touch screen registers input when a finger or other object comes in contact with the
screen.
When the wave signals are interrupted by some contact with the screen, that located is recorded.
Touch screens have long been used in military applications.
Voice Recognition is one of the newest, most complex input techniques used to interact with the
computer. The user inputs data by speaking into a microphone. The simplest form of voice
recognition is a one-word command spoken by one person. Each command is isolated with
pauses between the words.
Voice Recognition is used in some graphics workstations as input devices to accept voice
commands. The voice-system input can be used to initiate graphics operations or to enter data.
These systems operate by matching an input against a predefined dictionary of words and
phrases.
Advantage:
2. Easy to use
Disadvantages:
Image Scanner
It is an input device. The data or text is written on paper. The paper is feeded to scanner. The
paper written information is converted into electronic format; this format is stored in the
computer. The input documents can contain text, handwritten material, picture extra.
By storing the document in a computer document became safe for longer period of time. The
document will be permanently stored for the future. We can change the document when we need.
The document can be printed when needed.
Scanning can be of the black and white or colored picture. On stored picture 2D or 3D rotations,
scaling and other operations can be applied.
1. Flat Bed Scanner: It resembles a photocopy machine. It has a glass top on its top. Glass top
in further covered using a lid. The document to be scanned is kept on glass plate. The light is
passed underneath side of glass plate. The light is moved left to right. The scanning is done the
line by line. The process is repeated until the complete line is scanned. Within 20-25 seconds a
document of 4" * 6" can be scanned.
2. Hand Held Scanner: It has a number of LED's (Light Emitting Diodes) the LED's are
arranged in the small case. It is called a Hand held Scanner because it can be kept in hand which
performs scanning. For scanning the scanner is moved over document from the top towards the
bottom. Its light is on, while we move it on document. It is dragged very slowly over document.
If dragging of the scanner over the document is not proper, the conversion will not correct.
Output Devices
It is an electromechanical device, which accepts data from a computer and translates them into
form understand by users.
1. Printers
2. Plotters
Printers:
Printer is the most important output device, which is used to print data on paper.
Types of Printers: There are many types of printers which are classified on various criteria as
shown in fig:
1. Impact Printers: The printers that print the characters by striking against the ribbon and onto
the papers are known as Impact Printers.
1. Character Printers
2. Line Printers
2. Non-Impact Printers: The printers that print the characters without striking against the
ribbon and onto the papers are called Non-Impact Printers. These printers print a complete page
at a time, therefore, also known as Page Printers.
1. Laser Printers
2. Inkjet Printers
Dot matrix has printed in the form of dots. A printer has a head which contains nine pins. The
nine pins are arranged one below other. Each pin can be activated independently. All or only the
same needles are activated at a time. When needless is not activated, and then the tip of needle
stay in the head. When pin work, it comes out of the print head. In nine pin printer, pins are
arranged in 5 * 7 matrixes.
Advantage:
1. Dot Matrix Printers prints output as dots, so it can print any shape of the character. This
allows the printer to print special character, charts, graphs, etc.
2. Dot Matrix Printers come under the category of impact printers. The printing is done
when the hammer pin strikes the inked ribbon. The impressions are printed on paper. By
placing multiple copies of carbon, multiple copies of output can be produced.
Head is lying on a wheel and Pins corresponding to characters are like petals of Daisy, that's why
called Daisy wheel printer
Advantage:
2. Better Quality
Disadvantage:
Drum Printers:
These are line printers, which prints one line at a time. It consists of a drum. The shape of the
drum is cylindrical. The drum is solid and has characters embossed on it in the form of vertical
bands. The characters are in circular form. Each band consists of some characters. Each line on
drum consists of 132 characters. Because there are 96 lines so total characters are (132 * 95) =
12, 672.
Chain Printers:
These are called as line printers. These are used to print one line at a line. Basically, chain
consists of links. Each link contains one character. Printers can follow any character set style,
i.e., 48, 64 or 96 characters. Printer consists of a number of hammers also.
Advantages:
Disadvantages:
Non-Impact Printers:
Inkjet Printers:
These printers use a special link called electrostatic ink. The printer head has a special nozzle.
Nozzle drops ink on paper. Head contains up to 64 nozzles. The ink dropped is deflected by the
electrostatic plate. The plate is fixed outside the nozzle. The deflected ink settles on paper
Advantages:
Disadvantages:
Laser Printers:
These are non-impact page printers. They use laser lights to produces the dots needed to form the
characters to be printed on a page & hence the name laser printers.
Step1: The bits of data sent by processing unit act as triggers to turn the laser beam on & off.
Step2: The output device has a drum which is cleared & is given a positive electric charge. To
print a page the modulated laser beam passing from the laser scans back & forth the surface of
the drum. The positive electric charge on the drum is stored on just those parts of the drum
surface which are exposed to the laser beam create the difference in electric which charges on the
exposed drum surface.
Step3: The laser exposed parts of the drum attract an ink powder known as toner.
Step5: The ink particles are permanently fixed to the paper by using either heat or pressure
technique.
Step6: The drum rotates back to the cleaner where a rubber blade cleans off the excess ink &
prepares the drum to print the next page.
Plotters
Drum Plotter:
It consists of a drum. Paper on which design is made is kept on the drum. The drum can rotate in
both directions. Plotters comprised of one or more pen and penholders. The holders are mounted
perpendicular to drum surface. The pens are kept in the holder, which can move left to the right
as well as right to the left. The graph plotting program controls the movement of pen and drum.
Flatbed Plotter:
It is used to draw complex design and graphs, charts. The Flatbed plotter can be kept over the
table. The plotter consists of pen and holder. The pen can draw characters of various sizes. There
can be one or more pens and pen holding mechanism. Each pen has ink of different color.
Different colors help to produce multicolor design of document. The area of plotting is also
variable. It can vary A4 to 21'*52'.
It is used to draw
1. Cars
2. Ships
3. Airplanes
Graphics Software:
Example of general purpose package is the GL (Graphics Library), GKS, PHIGS, PHIGS+ etc.
2. Special Purpose Packages: These packages are designed for non-programmers, so that these
users can use the graphics packages, without knowing the inner details.
4. CAD packages
It is a process of representing graphics objects a collection of pixels. The graphics objects are
continuous. The pixels used are discrete. Each pixel can have either on or off state.
The circuitry of the video display device of the computer is capable of converting binary values
(0, 1) into a pixel on and pixel off information. 0 is represented by pixel off. 1 is represented
using pixel on. Using this ability graphics computer represent picture having discrete dots.
Any model of graphics can be reproduced with a dense matrix of dots or points. Most human
beings think graphics objects as points, lines, circles, ellipses. For generating graphical object,
many algorithms have been developed.
1. Point
2. Line
3. Sector
4. Arc
5. Ellipse
6. Rectangle
7. Polygon
8. Characters
9. Filled Regions
The process of converting is also called as rasterization. The algorithms implementation varies
from one computer system to another computer system. Some algorithms are implemented using
the software. Some are performed using hardware or firmware. Some are performed using
various combinations of hardware, firmware, and software.
Pixel or Pel:
The term pixel is a short form of the picture element. It is also called a point or dot. It is the
smallest picture unit accepted by display devices. A picture is constructed from hundreds of such
pixels. Pixels are generated using commands. Lines, circle, arcs, characters; curves are drawn
with closely spaced pixels. To display the digit or letter matrix of pixels is used.
The closer the dots or pixels are, the better will be the quality of picture. Closer the dots are,
crisper will be the picture. Picture will not appear jagged and unclear if pixels are closely spaced.
So the quality of the picture is directly proportional to the density of pixels on the screen.
Pixels are also defined as the smallest addressable unit or element of the screen. Each pixel can
be assigned an address as shown in fig:
Different graphics objects can be generated by setting the different intensity of pixels and
different colors of pixels. Each pixel has some co-ordinate value. The coordinate is represented
using row and column.
P (5, 5) used to represent a pixel in the 5th row and the 5th column. Each pixel has some
intensity value which is represented in memory of computer called a frame buffer. Frame
Buffer is also called a refresh buffer. This memory is a storage area for storing pixels values
using which pictures are displayed. It is also called as digital memory. Inside the buffer, image is
stored as a pattern of binary digits either 0 or 1. So there is an array of 0 or 1 used to represent
the picture. In black and white monitors, black pixels are represented using 1's and white pixels
are represented using 0's. In case of systems having one bit per pixel frame buffer is called a
bitmap. In systems with multiple bits per pixel it is called a pixmap.
Scan Converting a Point
Each pixel on the graphics display does not represent a mathematical point. Instead, it means a
region which theoretically can contain an infinite number of points. Scan-Converting a point
involves illuminating the pixel that contains the point.
A straight line may be defined by two endpoints & an equation. In fig the two endpoints are
described by (x1,y1) and (x2,y2). The equation of the line is used to determine the x, y coordinates
of all the points that lie between these two endpoints.
Using the equation of a straight line, y = mx + b where m = & b = the y interrupt, we can find
values of y by incrementing x from x =x1, to x = x2. By scan-converting these calculated x, y
values, we represent the line as a sequence of pixels.
1. Line should appear straight: We must appropriate the line by choosing addressable points
close to it. If we choose well, the line will appear straight, if not, we shall produce crossed lines.
The lines must be generated parallel or at 45° to the x and y-axes. Other lines cause a problem: a
line segment through it starts and finishes at addressable points, may happen to pass through no
another addressable points in between.
2. Lines should terminate accurately: Unless lines are plotted accurately, they may terminate
at the wrong place.
3. Lines should have constant density: Line density is proportional to the no. of dots displayed
divided by the length of the line.
4. Line density should be independent of line length and angle: This can be done by
computing an approximating line-length estimate and to use a line-generation algorithm that
keeps line density constant to within the accuracy of this estimate.
3. Bresenham's Algorithm
It is the simplest form of conversion. First of all scan P1 and P2 points. P1 has co-ordinates
(x1',y1') and (x2' y2' ).
Then m = (y2',y1')/( x2',x1') and b =
Example: A line with starting point as (0, 0) and ending point (6, 18) is given. Calculate value of
intermediate points and slope of line.
Solution: P1 (0,0) P7 (6,18)
x1=0
y1=0
x2=6
y2=18
put value of x from initial point in equation (1), i.e., (0, 0) x =0, y=0
0=3x0+b
0 = b ⟹ b=0
Step1: Start Algorithm
Step4: Calculate dx = x2- x1
Step5: Calculate dy = y2-y1
Step6: Calculate m =
Step7: Calculate b = y1-m* x1
Step8: Set (x, y) equal to starting point, i.e., lowest point and xendequal to largest value of x.
If dx < 0
then x = x2
y = y2
xend= x1
If dx > 0
then x = x1
y = y1
xend= x2
Step9: Check whether the complete line has been drawn if x=xend, stop
Step13: Go to Step9.
1. #include <graphics.h>
2. #include <stdlib.h>
3. #include <math.h>
4. #include <stdio.h>
5. #include <conio.h>
6. #include <iostream.h>
7.
8. class bresen
9. {
10. float x, y, x1, y1, x2, y2, dx, dy, m, c, xend;
11. public:
12. void get ();
13. void cal ();
14. };
15. void main ()
16. {
17. bresen b;
18. b.get ();
19. b.cal ();
20. getch ();
21. }
22. Void bresen :: get ()
23. {
24. print ("Enter start & end points");
25. print ("enter x1, y1, x2, y2");
26. scanf ("%f%f%f%f",sx1, sx2, sx3, sx4)
27. }
28. void bresen ::cal ()
29. {
30. /* request auto detection */
31. int gdriver = DETECT,gmode, errorcode;
32. /* initialize graphics and local variables */
33. initgraph (&gdriver, &gmode, " ");
34. /* read result of initialization */
35. errorcode = graphresult ();
36. if (errorcode ! = grOK) /*an error occurred */
37. {
38. printf("Graphics error: %s \n", grapherrormsg (errorcode);
39. printf ("Press any key to halt:");
40. getch ();
41. exit (1); /* terminate with an error code */
42. }
43. dx = x2-x1;
44. dy=y2-2y1;
45. m = dy/dx;
46. c = y1 - (m * x1);
47. if (dx<0)
48. {
49. x=x2;
50. y=y2;
51. xend=x1;
52. }
53. else
54. {
55. x=x1;
56. y=y1;
57. xend=x2;
58. }
59. while (x<=xend)
60. {
61. putpixel (x, y, RED);
62. y++;
63. y=(x*x) +c;
64. }
65. }
OUTPUT:
DDA stands for Digital Differential Analyzer. It is an incremental method of scan conversion of
line. In this method calculation is performed at each step but by using results of previous steps.
m=
yi+1-yi=∆y.......................equation 3
yi+1-xi=∆x......................equation 4
yi+1=yi+∆y
∆y=m∆x
yi+1=yi+m∆x
∆x=∆y/m
xi+1=xi+∆x
xi+1=xi+∆y/m
xi+1= , y=y+1
Until y → y2</y
Advantage:
Disadvantage:
1. It involves floating point additions rounding off is done. Accumulations of round off
error cause accumulation of error.
2. Rounding off operations and floating point operations consumes a lot of time.
3. It is more suitable for generating line using the software. But it is less suited for hardware
implementation.
DDA Algorithm:
Step1: Start Algorithm
Step4: Calculate dx = x2-x1
Step5: Calculate dy = y2-y1
Step7: xinc=dx/step
yinc=dy/step
assign x = x1
assign y = y1
Step9: x = x + xinc
y = y + yinc
Set pixels (Round (x), Round (y))
Step11: End Algorithm
Example: If a line is drawn from (2, 3) to (6, 15) with use of DDA. How many points will
needed to generate such line?
Solution: P1 (2,3) P11 (6,15)
x1=2
y1=3
x2= 6
y2=15
dx = 6 - 2 = 4
dy = 15 - 3 = 12
m =
1. #include<graphics.h>
2. #include<conio.h>
3. #include<stdio.h>
4. void main()
5. {
6. intgd = DETECT ,gm, i;
7. float x, y,dx,dy,steps;
8. int x0, x1, y0, y1;
9. initgraph(&gd, &gm, "C:\\TC\\BGI");
10. setbkcolor(WHITE);
11. x0 = 100 , y0 = 200, x1 = 500, y1 = 300;
12. dx = (float)(x1 - x0);
13. dy = (float)(y1 - y0);
14. if(dx>=dy)
15. {
16. steps = dx;
17. }
18. else
19. {
20. steps = dy;
21. }
22. dx = dx/steps;
23. dy = dy/steps;
24. x = x0;
25. y = y0;
26. i = 1;
27. while(i<= steps)
28. {
29. putpixel(x, y, RED);
30. x += dx;
31. y += dy;
32. i=i+1;
33. }
34. getch();
35. closegraph();
36. }
Output:
Symmetrical DDA:
The Digital Differential Analyzer (DDA) generates lines from their differential equations. The
equation of a straight line is
The DDA works on the principle that we simultaneously increment x and y by small steps
proportional to the first derivatives of x and y. In this case of a straight line, the first derivatives
are constant and are proportional to ∆x and ∆y . Therefore, we could generate a line by
incrementing x and y by ϵ ∆x and ϵ ∆y, where ϵ is some small quantity. There are two ways to
generate points
1. By rounding to the nearest integer after each incremental step, after rounding we display dots
at the resultant x and y.
2. An alternative to rounding the use of arithmetic overflow: x and y are kept in registers that
have two parts, integer and fractional. The incrementing values, which are both less than unity,
are repeatedly added to the fractional parts and whenever the results overflows, the
corresponding integer part is incremented. The integer parts of the x and y registers are used in
plotting the line. In the case of the symmetrical DDA, we choose ε=2-n,where 2n-1≤max (|∆x|,|
∆y|)<2π
This algorithm is used for scan converting a line. It was developed by Bresenham. It is an
efficient method because it involves only integer addition, subtractions, and multiplication
operations. These operations can be performed very rapidly so lines can be generated quickly.
In this method, next pixel selected is that one who has the least distance from true line.
Assume a pixel P1'(x1',y1'),then select subsequent pixels as we work our way to the night, one
pixel position at a time in the horizontal direction toward P2'(x2',y2').
The line is best approximated by those pixels that fall the least distance from the path between
P1',P2'.
To chooses the next one between the bottom pixel S and top pixel T.
If S is chosen
We have xi+1=xi+1 and yi+1=yi
If T is chosen
We have xi+1=xi+1 and yi+1=yi+1
This difference is
s-t = (y-yi)-[(yi+1)-y]
= 2y - 2yi -1
Special Cases
Finally, we calculate d1
d1=△x[2m(x1+1)+2b-2y1-1]
d1=△x[2(mx1+b-y1)+2m-1]
Since mx1+b-yi=0 and m = , we have
d1=2△y-△x
Advantage:
3. It can be implemented using hardware because it does not use multiplication and division.
4. It is faster as compared to DDA (Digital Differential Analyzer) because it does not involve
floating point calculations like DDA Algorithm.
Disadvantage:
1. This algorithm is meant for basic line drawing only Initializing is not a part of Bresenham's
line algorithm. So to draw smooth lines, you should want to look into a different algorithm.
Step1: Start Algorithm
Step4: Calculate dx = x2-x1
Calculate dy = y2-y1
Calculate i1=2*dy
Calculate i2=2*(dy-dx)
Calculate d=i1-dx
Step9: Increment x = x + 1
Step11: Go to step 7
Step12: End of Algorithm
Example: Starting and Ending position of the line are (1, 1) and (8, 5). Find intermediate points.
Solution: x1=1
y1=1
x2=8
y2=5
dx= x2-x1=8-1=7
dy=y2-y1=5-1=4
I1=2* ∆y=2*4=8
I2=2*(∆y-∆x)=2*(4-7)=-6
d = I1-∆x=8-7=1
x y d=d+I1 or I2
1 1 d+I2=1+(-6)=-5
2 2 d+I1=-5+8=3
3 2 d+I2=3+(-6)=-3
4 3 d+I1=-3+8=5
5 3 d+I2=5+(-6)=-1
6 4 d+I1=-1+8=7
7 4 d+I2=7+(-6)=1
8 5
1. #include<stdio.h>
2. #include<graphics.h>
3. void drawline(int x0, int y0, int x1, int y1)
4. {
5. int dx, dy, p, x, y;
6. dx=x1-x0;
7. dy=y1-y0;
8. x=x0;
9. y=y0;
10. p=2*dy-dx;
11. while(x<x1)
12. {
13. if(p>=0)
14. {
15. putpixel(x,y,7);
16. y=y+1;
17. p=p+2*dy-2*dx;
18. }
19. else
20. {
21. putpixel(x,y,7);
22. p=p+2*dy;}
23. x=x+1;
24. }
25. }
26. int main()
27. {
28. int gdriver=DETECT, gmode, error, x0, y0, x1, y1;
29. initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");
30. printf("Enter co-ordinates of first point: ");
31. scanf("%d%d", &x0, &y0);
32. printf("Enter co-ordinates of second point: ");
33. scanf("%d%d", &x1, &y1);
34. drawline(x0, y0, x1, y1);
35. return 0;
36. }
Output:
1. DDA Algorithm use floating point, i.e., Real 1. Bresenham's Line Algorithm use fixed point, i.e.,
Arithmetic. Integer Arithmetic
2. DDA Algorithms uses multiplication & 2.Bresenham's Line Algorithm uses only subtraction
division its operation and addition its operation
3. DDA Algorithm is slowly than Bresenham's 3. Bresenham's Algorithm is faster than DDA
Line Algorithm in line drawing because it uses Algorithm in line because it involves only addition &
real arithmetic (Floating Point operation) subtraction in its calculation and uses only integer
arithmetic.
4. DDA Algorithm is not accurate and efficient 4. Bresenham's Line Algorithm is more accurate and
as Bresenham's Line Algorithm. efficient at DDA Algorithm.
5.DDA Algorithm can draw circle and curves 5. Bresenham's Line Algorithm can draw circle and
but are not accurate as Bresenham's Line curves with more accurate than DDA Algorithm.
Algorithm
Defining a Circle:
Circle is an eight-way symmetric figure. The shape of circle is the same in all quadrants. In each
quadrant, there are two octants. If the calculation of the point of one octant is done, then the
other seven points can be calculated easily by using the concept of eight-way symmetry.
For drawing, circle considers it at the origin. If a point is P1(x, y), then the other seven points will
be
So we will calculate only 45°arc. From which the whole circle can be determined easily.
If we want to display circle on screen then the putpixel function is used for eight points as shown
below:
Example: Let we determine a point (2, 7) of the circle then other points will be (2, -7), (-2, -7),
(-2, 7), (7, 2), (-7, 2), (-7, -2), (7, -2)
These seven points are calculated by using the property of reflection. The reflection is
accomplished in the following way:
There are two standards methods of mathematically defining a circle centered at the origin.
The first method defines a circle with the second-order polynomial equation as shown in fig:
y2=r2-x2
Where x = the x coordinate
y = the y coordinate
r = the circle radius
With the method, each x coordinate in the sector, from 90° to 45°, is found by stepping x from 0
Algorithm:
xend=
Step2: Test to determine whether the entire circle has been scan-converted.
Step3: Compute y =
Step4: Plot the eight points found by symmetry concerning the center (h, k) at the current (x, y)
coordinates.
Step5: Increment x = x + i
1. #include<graphics.h>
2. #include<conio.h>
3. #include<math.h>
4. voidsetPixel(int x, int y, int h, int k)
5. {
6. putpixel(x+h, y+k, RED);
7. putpixel(x+h, -y+k, RED);
8. putpixel(-x+h, -y+k, RED);
9. putpixel(-x+h, y+k, RED);
10. putpixel(y+h, x+k, RED);
11. putpixel(y+h, -x+k, RED);
12. putpixel(-y+h, -x+k, RED);
13. putpixel(-y+h, x+k, RED);
14. }
15. main()
16. {
17. intgd=0, gm,h,k,r;
18. double x,y,x2;
19. h=200, k=200, r=100;
20. initgraph(&gd, &gm, "C:\\TC\\BGI ");
21. setbkcolor(WHITE);
22. x=0,y=r;
23. x2 = r/sqrt(2);
24. while(x<=x2)
25. {
26. y = sqrt(r*r - x*x);
27. setPixel(floor(x), floor(y), h,k);
28. x += 1;
29. }
30. getch();
31. closegraph();
32. return 0;
33. }
Output:
Defining a circle using Polar Co-ordinates :
The second method of defining a circle makes use of polar coordinates as shown in fig:
By this method, θ is stepped from 0 to & each value of x & y is calculated.
Algorithm:
r = circle radius
(h, k) = coordinates of the circle center
i = step size
θ_end=
θ=0
Step3: Compute
x = r * cos θ y=r*sin?θ
Step4: Plot the eight points, found by symmetry i.e., the center (h, k), at the current (x, y)
coordinates.
Step5: Increment θ=θ+i
1. #include <graphics.h>
2. #include <stdlib.h>
3. #define color 10
4. void eightWaySymmetricPlot(int xc,int yc,int x,int y)
5. {
6. putpixel(x+xc,y+yc,color);
7. putpixel(x+xc,-y+yc,color);
8. putpixel(-x+xc,-y+yc,color);
9. putpixel(-x+xc,y+yc,color);
10. putpixel(y+xc,x+yc,color);
11. putpixel(y+xc,-x+yc,color);
12. putpixel(-y+xc,-x+yc,color);
13. putpixel(-y+xc,x+yc,color);
14. }
15. void PolarCircle(int xc,int yc,int r)
16. {
17. int x,y,d;
18. x=0;
19. y=r;
20. d=3-2*r;
21. eightWaySymmetricPlot(xc,yc,x,y);
22. while(x<=y)
23. {
24. if(d<=0)
25. {
26. d=d+4*x+6;
27. }
28. else
29. {
30. d=d+4*x-4*y+10;
31. y=y-1;
32. }
33. x=x+1;
34. eightWaySymmetricPlot(xc,yc,x,y);
35. }
36. }
37. int main(void)
38. {
39. int gdriver = DETECT, gmode, errorcode;
40. int xc,yc,r;
41. initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");
42. errorcode = graphresult();
43. if (errorcode != grOk)
44. {
45. printf("Graphics error: %s\n", grapherrormsg(errorcode));
46. printf("Press any key to halt:");
47. getch();
48. exit(1);
49. }
50. printf("Enter the values of xc and yc ,that is center points of circle : ");
51. scanf("%d%d",&xc,&yc);
52. printf("Enter the radius of circle : ");
53. scanf("%d",&r);
54. PolarCircle(xc,yc,r);
55. getch();
56. closegraph();
57. return 0;
58. }
Output:
Scan-Converting a circle using Bresenham's algorithm works as follows: Points are generated
from 90° to 45°, moves will be made only in the +x & -y directions as shown in fig:
The best approximation of the true circle will be described by those pixels in the raster that falls
the least distance from the true circle. We want to generate the points from.
90° to 45°. Assume that the last scan-converted pixel is P1 as shown in fig. Each new point
closest to the true circle can be found by taking either of two actions.
2. Move in the x- direction one unit & move in the negative y-direction one unit.
Let D (Si) is the distance from the origin to the true circle squared minus the distance to point
P3 squared. D (Ti) is the distance from the origin to the true circle squared minus the distance to
point P2 squared. Therefore, the following expressions arise.
D (Si)=(xi-1+1)2+ yi-12 -r2
D (Ti)=(xi-1+1)2+(yi-1 -1)2-r2
Since D (Si) will always be +ve & D (Ti) will always be -ve, a decision variable d may be
defined as follows:
Therefore,
di=(xi-1+1)2+ yi-12 -r2+(xi-1+1)2+(yi-1 -1)2-r2
If it is assumed that the circle is centered at the origin, then at the first step x = 0 & y = r.
Therefore,
di=(0+1)2+r2 -r2+(0+1)2+(r-1)2-r2
=1+1+r2-2r+1-r2
= 3 - 2r
Step1: Start Algorithm
Step2: Declare p, q, x, y, r, d variables
p, q are coordinates of the center of the circle
r is the radius of the circle
Step4: Calculate d = 3 - 2r
Step5: Initialize x=0
&nbsy= r
Step7: Plot eight points by using concepts of eight-way symmetry. The center is at (p, q).
Current active pixel is (x, y).
putpixel (x+p, y+q)
putpixel (y+p, x+q)
putpixel (-y+p, x+q)
putpixel (-x+p, y+q)
putpixel (-x+p, -y+q)
putpixel (-y+p, -x+q)
putpixel (y+p, -x+q)
putpixel (x+p, -y-q)
Step9: Go to step 6
Step10: Stop Algorithm
Example: Plot 6 points of circle using Bresenham Algorithm. When radius of circle is 10 units.
The circle has centre (50, 50).
Solution: Let r = 10 (Given)
Step1: Take initial point (0, 10)
d = 3 - 2r
d = 3 - 2 * 10 = -17
d < 0 ∴ d = d + 4x + 6
= -17 + 4 (0) + 6
= -11
Step5: Plot (4, 9)
d = -1 + 4x + 6
= -1 + 4 (4) + 6
= 21
Step6: Plot (5, 8)
d = d + 4 (x-y) + 10 (∵ d > 0)
= 21 + 4 (5-8) + 10
= 21-12 + 10 = 19
So P1 (0,0)⟹(50,50)
P2 (1,10)⟹(51,60)
P3 (2,10)⟹(52,60)
P4 (3,9)⟹(53,59)
P5 (4,9)⟹(54,59)
P6 (5,8)⟹(55,58)
1. #include <graphics.h>
2. #include <stdlib.h>
3. #include <stdio.h>
4. #include <conio.h>
5. #include <math.h>
6.
7. void EightWaySymmetricPlot(int xc,int yc,int x,int y)
8. {
9. putpixel(x+xc,y+yc,RED);
10. putpixel(x+xc,-y+yc,YELLOW);
11. putpixel(-x+xc,-y+yc,GREEN);
12. putpixel(-x+xc,y+yc,YELLOW);
13. putpixel(y+xc,x+yc,12);
14. putpixel(y+xc,-x+yc,14);
15. putpixel(-y+xc,-x+yc,15);
16. putpixel(-y+xc,x+yc,6);
17. }
18.
19. void BresenhamCircle(int xc,int yc,int r)
20. {
21. int x=0,y=r,d=3-(2*r);
22. EightWaySymmetricPlot(xc,yc,x,y);
23.
24. while(x<=y)
25. {
26. if(d<=0)
27. {
28. d=d+(4*x)+6;
29. }
30. else
31. {
32. d=d+(4*x)-(4*y)+10;
33. y=y-1;
34. }
35. x=x+1;
36. EightWaySymmetricPlot(xc,yc,x,y);
37. }
38. }
39.
40. int main(void)
41. {
42. /* request auto detection */
43. int xc,yc,r,gdriver = DETECT, gmode, errorcode;
44. /* initialize graphics and local variables */
45. initgraph(&gdriver, &gmode, "C:\\TURBOC3\\BGI");
46.
47. /* read result of initialization */
48. errorcode = graphresult();
49.
50. if (errorcode != grOk) /* an error occurred */
51. {
52. printf("Graphics error: %s\n", grapherrormsg(errorcode));
53. printf("Press any key to halt:");
54. getch();
55. exit(1); /* terminate with an error code */
56. }
57. printf("Enter the values of xc and yc :");
58. scanf("%d%d",&xc,&yc);
59. printf("Enter the value of radius :");
60. scanf("%d",&r);
61. BresenhamCircle(xc,yc,r);
62.
63. getch();
64. closegraph();
65. return 0;
66. }
Output:
It is based on the following function for testing the spatial relationship between the arbitrary
point (x, y) and a circle of radius r centered at the origin:
Now, consider the coordinates of the point halfway between pixel T and pixel S
If Pi is+ve ⟹midpoint is outside the circle (or on the circle)and we choose pixel S.
We have yi+1=yi-1
We can put ≅1
∴r is an integer
So, P1=1-r
Algorithm:
Step3: End
1. #include <graphics.h>
2. #include <stdlib.h>
3. #include <math.h>
4. #include <stdio.h>
5. #include <conio.h>
6. #include <iostream.h>
7.
8. class bresen
9. {
10. float x, y,a, b, r, p;
11. public:
12. void get ();
13. void cal ();
14. };
15. void main ()
16. {
17. bresen b;
18. b.get ();
19. b.cal ();
20. getch ();
21. }
22. Void bresen :: get ()
23. {
24. cout<<"ENTER CENTER AND RADIUS";
25. cout<< "ENTER (a, b)";
26. cin>>a>>b;
27. cout<<"ENTER r";
28. cin>>r;
29. }
30. void bresen ::cal ()
31. {
32. /* request auto detection */
33. int gdriver = DETECT,gmode, errorcode;
34. int midx, midy, i;
35. /* initialize graphics and local variables */
36. initgraph (&gdriver, &gmode, " ");
37. /* read result of initialization */
38. errorcode = graphresult ();
39. if (errorcode ! = grOK) /*an error occurred */
40. {
41. printf("Graphics error: %s \n", grapherrormsg (errorcode);
42. printf ("Press any key to halt:");
43. getch ();
44. exit (1); /* terminate with an error code */
45. }
46. x=0;
47. y=r;
48. putpixel (a, b+r, RED);
49. putpixel (a, b-r, RED);
50. putpixel (a-r, b, RED);
51. putpixel (a+r, b, RED);
52. p=5/4)-r;
53. while (x<=y)
54. {
55. If (p<0)
56. p+= (4*x)+6;
57. else
58. {
59. p+=(2*(x-y))+5;
60. y--;
61. }
62. x++;
63. putpixel (a+x, b+y, RED);
64. putpixel (a-x, b+y, RED);
65. putpixel (a+x, b-y, RED);
66. putpixel (a+x, b-y, RED);
67. putpixel (a+x, b+y, RED);
68. putpixel (a+x, b-y, RED);
69. putpixel (a-x, b+y, RED);
70. putpixel (a-x, b-y, RED);
71. }
72. }
Output:
SCAN CONVERTING ELLIPSE
The ellipse is also a symmetric figure like a circle but is four-way symmetry rather than eight-
way.
Program to Implement Ellipse Drawing Algorithm:
1. #include<stdio.h>
2. #include<conio.h>
3. #include<graphics.h>
4. #include<math.h>
5. void disp();
6. float x,y;
7. intxc,yc;
8. void main()
9. {
10. intgd=DETECT,gm,a,b;
11. float p1,p2;
12. clrscr();
13. initgraph(&gd,&gm,"c:\\turboc3\\bgi");
14. printf("*** Ellipse Generating Algorithm ***\n");
15. printf("Enter the value of Xc\t");
16. scanf("%d",&xc);
17. printf("Enter the value of yc\t");
18. scanf("%d",&yc);
19. printf("Enter X axis length\t");
20. scanf("%d",&a);
21. printf("Enter Y axis length\t");
22. scanf("%d",&b);
23. x=0;y=b;
24. disp();
25. p1=(b*b)-(a*a*b)+(a*a)/4;
26. while((2.0*b*b*x)<=(2.0*a*a*y))
27. {
28. x++;
29. if(p1<=0)
30. p1=p1+(2.0*b*b*x)+(b*b);
31. else
32. {
33. y--;
34. p1=p1+(2.0*b*b*x)+(b*b)-(2.0*a*a*y);
35. }
36. disp();
37. x=-x;
38. disp();
39. x=-x;
40. delay(50);
41. }
42. x=a;
43. y=0;
44. disp();
45. p2=(a*a)+2.0*(b*b*a)+(b*b)/4;
46. while((2.0*b*b*x)>(2.0*a*a*y))
47. {
48. y++;
49. if(p2>0)
50. p2=p2+(a*a)-(2.0*a*a*y);
51. else
52. {
53. x--;
54. p2=p2+(2.0*b*b*x)-(2.0*a*a*y)+(a*a);
55. }
56. disp();
57. y=-y;
58. disp();
59. y=-y;
60. delay(50);
61. }
62. getch();
63. closegraph();
64. }
65. void disp()
66. {
67. putpixel(xc+x,yc+y,7);
68. putpixel(xc-x,yc+y,7);
69. putpixel(xc+x,yc-y,7);
70. putpixel(xc+x,yc-y,7);
71. }
Output:
There two methods of defining an Ellipse:
Polynomial Method:
The ellipse has a major and minor axis. If a1 and b1are major and minor axis respectively. The
centre of ellipse is (i, j). The value of x will be incremented from i to a1and value of y will be
calculated using the following formula
2. Routines developed for such calculations are very complex and slow.
Algorithm:
1. Set the initial variables: a = length of major axis; b = length of minor axis; (h, k) = coordinates
of ellipse center; x = 0; i = step; xend = a.
2. Test to determine whether the entire ellipse has been scan-converted. If x>xend, stop.
4. Plot the four points, found by symmetry, at the current (x, y) coordinates:
5. Increment x; x = x + i.
6. Go to step 2.
1. #include <graphics.h>
2. #include <stdlib.h>
3. #include <math.h>
4. #include <stdio.h>
5. #include <conio.h>
6. #include <iostream.h>
7.
8. class bresen
9. {
10. float x, y, a, b, r, t, te, xend, h, k, step;
11. public:
12. void get ();
13. void cal ();
14. };
15. void main ()
16. {
17. bresen b;
18. b.get ();
19. b.cal ();
20. getch ();
21. }
22. void bresen :: get ()
23. {
24. cout<<"\n ENTER CENTER OF ELLIPSE";
25. cout<<"\n enter (h, k) ";
26. cin>>h>>k;
27. cout<<"\n ENTER LENGTH OF MAJOR AND MINOR AXIS";
28. cin>>a>>b;
29. cout<<"\n ENTER Step Size";
30. cin>> step;
31. }
32. void bresen ::cal ()
33. {
34. /* request auto detection */
35. int gdriver = DETECT,gmode, errorcode;
36. int midx, midy, i;
37. /* initialize graphics and local variables */
38. initgraph (&gdriver, &gmode, " ");
39. /* read result of initialization */
40. errorcode = graphresult ();
41. if (errorcode ! = grOK) /*an error occurred */
42. {
43. printf("Graphics error: %s \n", grapherrormsg (errorcode);
44. printf ("Press any key to halt:");
45. getch ();
46. exit (1); /* terminate with an error code */
47. }
48. x = 0;
49. xend=a;
50. whilex (x<xend)
51. {
52. t= (1-((x * x)/ (a * a)));
53. if (t<0)
54. te=-t;
55. else
56. te=t;
57. y=b * sqrt (te);
58. putpixel (h+x, k+y, RED);
59. putpixel (h-x, k+y, RED);
60. putpixel (h+x, y-y, RED);
61. putpixel (h-x, k-y, RED);
62. x+=step;
63. }
64. getch();
65. }
Output:
Trignometric Method:
In this method, the value of θ is varied from 0 to radians. The remaining points are found by
symmetry.
Drawback:
Step1: Start Algorithm
Step4: Calculate aa1=a1*a1
Calculate bb1=b1* b1
Calculate aa2=aa1*2
Calculate bb2=bb1*2
Step5: Initialize fx = 0
Step6: Initialize fy = aa_2* b1
Step8:
Increment x i.e., x = x + 1
Calculate fx = fx + bb2
If (p1 < 0)
Calculate p1 = p1 + fx + bb1/
else
Calculate fy = fy - 992;
p1=p1 + fx + bb1-fy
Step9: Setpixel (x1,y1)
Step10: Calculate p1=bb1 (x+.5)(x+.5)+aa(y-1)(y-1)-aa1*bb1
Step 11:
While (y1>0)
fy=fx-aa2/
if (p1>=0)
p1=p1 - fx + aa1/
else
Increment x i.e., x = x + 1
fx= fx+bb_2
p1=p1+fx-fy-aa1
Step12: Stop Algorithm
1. #include <graphics.h>
2. #include <stdlib.h>
3. #include <math.h>
4. #include <stdio.h>
5. #include <conio.h>
6. #include <iostream.h>
7. # define pi 3.14
8.
9. class bresen
10. {
11. float a, b, h, k, thetaend,step,x,y;
12. int i;
13. public:
14. void get ();
15. void cal ();
16. };
17. void main ()
18. {
19. bresen b;
20. b.get ();
21. b.cal ();
22. getch ();
23. }
24. void bresen :: get ()
25. {
26. cout<<"\n ENTER CENTER OF ELLIPSE";
27. cin>>h>>k;
28. cout<<"\n ENTER LENGTH OF MAJOR AND MINOR AXIS";
29. cin>>a>>b;
30. cout<<"\n ENTER STEP SIZE";
31. cin>> step;
32. }
33. void bresen ::cal ()
34. {
35. /* request auto detection */
36. int gdriver = DETECT,gmode, errorcode;
37. int midx, midy, i;
38. /* initialize graphics and local variables */
39. initgraph (&gdriver, &gmode, " ");
40. /* read result of initialization */
41. errorcode = graphresult ();
42. if (errorcode ! = grOK) /*an error occurred */
43. {
44. printf("Graphics error: %s \n", grapherrormsg (errorcode);
45. printf ("Press any key to halt:");
46. getch ();
47. exit (1); /* terminate with an error code */
48. }
49. theta= 0;
50. thetaend=(pi*90)/180;
51. whilex (theta<thetaend)
52. {
53. x = a * cos (theta);
54. y = b * sin (theta);
55. putpixel (x+h, y+k, RED);
56. putpixel (-x+h, y+k, RED);
57. putpixel (-x+h, -y+k, RED);
58. putpixel (x+h, -y+k, RED);
59. theta+=step;
60. }
61. getch();
62. }
Output:
Since the ellipse shows four-way symmetry, it can easily be rotated. The new equation is found
by trading a and b, the values which describe the major and minor axes. When the polynomial
method is used, the equations used to describe the ellipse become
This is an incremental method for scan converting an ellipse that is centered at the origin in
standard position i.e., with the major and minor axis parallel to coordinate system axis. It is very
similar to the midpoint circle algorithm. Because of the four-way symmetry property we need to
consider the entire elliptical curve in the first quadrant.
Let's first rewrite the ellipse equation and define the function f that can be used to decide if the
midpoint between two candidate pixels is inside or outside the ellipse:
Now divide the elliptical curve from (0, b) to (a, 0) into two parts at point Q where the slope of
the curve is -1.
Slope of the curve is defined by the f(x, y) = 0 is where fx & fy are partial derivatives
of f(x, y) with respect to x & y.
We have fx = 2b2 x, fy=2a2 y & Hence we can monitor the slope value during the
scan conversion process to detect Q. Our starting point is (0, b)
Suppose that the coordinates of the last scan converted pixel upon entering step i are (xi,yi). We
are to select either T (xi+1),yi) or S (xi+1,yi-1) to be the next pixel. The midpoint of T & S is used to
define the following decision parameter.
pi = f(xi+1),yi- )
pi=b2 (xi+1)2+a2 (yi- )2-a2 b2
pi+1=f(xi+1+1,yi+1- )
= b2 (xi+1+1)2+a2 (yi+1- )2-a2 b2
The initial value for the recursive expression can be obtained by the evaluating the original
definition of pi with (0, b):
p1 = (b2+a2 (b- )2-a2 b2
= b2-a2 b+a2/4
Suppose the pixel (xj yj) has just been scan converted upon entering step j. The next pixel is
either U (xj ,yj-1) or V (xj+1,yj-1). The midpoint of the horizontal line connecting U & V is used
to define the decision parameter:
qj=f(xj+ ,yj-1)
qj=b2 (xj+ )2+a2 (yj -1)2-a2 b2
If qj≥0, the midpoint is outside the curve and we choose pixel U.Decision parameter for the next
step is:
qj+1=f(xj+1+ ,yj+1-1)
The initial value for the recursive expression is computed using the original definition of qj. And
the coordinates of (xk yk) of the last pixel choosen for the part 1 of the curve:
Algorithm:
while (fx<="" 1="" {="" set="" pixel="" (x,="" y)="" x++;="" fx="fx" +="" 2b2;
if (p<0)
p = p + fx +b2;
else
y--;
fy=fy-2a2
p = p + fx +b2-fy;
p=b2(x+0.5)2+ a2 (y-1)2- a2 b2
while (y>0)
y--;
fy=fy-2a2;
if (p>=0)
p=p-fy+a2
else
x++;
fx=fx+2b2
p=p+fx-fy+a2;
Setpixel (x,y);
1. #include <graphics.h>
2. #include <stdlib.h>
3. #include <math.h>
4. #include <stdio.h>
5. #include <conio.h>
6. #include <iostream.h>
7.
8. class bresen
9. {
10. float x,y,a, b,r,p,h,k,p1,p2;
11. public:
12. void get ();
13. void cal ();
14. };
15. void main ()
16. {
17. bresen b;
18. b.get ();
19. b.cal ();
20. getch ();
21. }
22. void bresen :: get ()
23. {
24. cout<<"\n ENTER CENTER OF ELLIPSE";
25. cout<<"\n ENTER (h, k) ";
26. cin>>h>>k;
27. cout<<"\n ENTER LENGTH OF MAJOR AND MINOR AXIS";
28. cin>>a>>b;
29. }
30. void bresen ::cal ()
31. {
32. /* request auto detection */
33. int gdriver = DETECT,gmode, errorcode;
34. int midx, midy, i;
35. /* initialize graphics and local variables */
36. initgraph (&gdriver, &gmode, " ");
37. /* read result of initialization */
38. errorcode = graphresult ();
39. if (errorcode ! = grOK) /*an error occurred */
40. {
41. printf("Graphics error: %s \n", grapherrormsg (errorcode);
42. printf ("Press any key to halt:");
43. getch ();
44. exit (1); /* terminate with an error code */
45. }
46. x=0;
47. y=b;
48. // REGION 1
49. p1 =(b * b)-(a * a * b) + (a * a)/4);
50. {
51. putpixel (x+h, y+k, RED);
52. putpixel (-x+h, -y+k, RED);
53. putpixel (x+h, -y+k, RED);
54. putpixel (-x+h, y+k, RED);
55. if (p1 < 0)
56. p1 += ((2 *b * b) *(x+1))-((2 * a * a)*(y-1)) + (b * b);
57. else
58. {
59. p1+= ((2 *b * b) *(x+1))-((2 * a * a)*(y-1))-(b * b);
60. y--;
61. }
62. x++;
63. }
64. //REGION 2
65. p2 =((b * b)* (x + 0.5))+((a * a)*(y-1) * (y-1))-(a * a *b * b);
66. while (y>=0)
67. {
68. If (p2>0)
69. p2=p2-((2 * a * a)* (y-1))+(a *a);
70. else
71. {
72. p2=p2-((2 * a * a)* (y-1))+((2 * b * b)*(x+1))+(a * a);
73. x++;
74. }
75. y--;
76. putpixel (x+h, y+k, RED);
77. putpixel (-x+h, -y+k, RED);
78. putpixel (x+h, -y+k, RED);
79. putpixel (-x+h, y+k, RED);
80. }
81. getch();
82. }
Output:
FILLED AREA PRIMITIVES
Region filling is the process of filling image or region. Filling can be of boundary or interior
region as shown in fig. Boundary Fill algorithms are used to fill the boundary and flood-fill
algorithm are used to fill the interior.
This algorithm uses the recursive method. First of all, a starting pixel called as the seed is
considered. The algorithm checks boundary pixel or adjacent pixels are colored or not. If the
adjacent pixel is already filled or colored then leave it, otherwise fill it. The filling is done using
four connected or eight connected approaches.
Four connected approaches is more suitable than the eight connected approaches.
1. Four connected approaches: In this approach, left, right, above, below pixels are tested.
2. Eight connected approaches: In this approach, left, right, above, below and four diagonals
are selected.
Boundary can be checked by seeing pixels from left and right first. Then pixels are checked by
seeing pixels from top to bottom. The algorithm takes time and memory because some recursive
calls are needed.
It may not fill regions sometimes correctly when some interior pixel is already filled with color.
The algorithm will check this boundary pixel for filling and will found already filled so recursive
process will terminate. This may vary because of another interior pixel unfilled.
Algorithm:
1. Procedure fill (x, y, color, color1: integer)
2. int c;
3. c=getpixel (x, y);
4. if (c!=color) (c!=color1)
5. {
6. setpixel (x, y, color)
7. fill (x+1, y, color, color 1);
8. fill (x-1, y, color, color 1);
9. fill (x, y+1, color, color 1);
10. fill (x, y-1, color, color 1);
11. }
In this method, a point or seed which is inside region is selected. This point is called a seed point.
Then four connected approaches or eight connected approaches is used to fill with specified
color.
The flood fill algorithm has many characters similar to boundary fill. But this method is more
suitable for filling multiple colors boundary. When boundary is of many colors and interior is to
be filled with one color we use this algorithm.
In fill algorithm, we start from a specified interior point (x, y) and reassign all pixel values are
currently set to a given interior color with the desired color. Using either a 4-connected or 8-
connected approaches, we then step through pixel positions until all interior points have been
repainted.
Disadvantage:
Algorithm:
1. Procedure floodfill (x, y,fill_ color, old_color: integer)
2. If (getpixel (x, y)=old_color)
3. {
4. setpixel (x, y, fill_color);
5. fill (x+1, y, fill_color, old_color);
6. fill (x-1, y, fill_color, old_color);
7. fill (x, y+1, fill_color, old_color);
8. fill (x, y-1, fill_color, old_color);
9. }
10. }
Program1: To implement 4-connected flood fill algorithm:
1. #include<stdio.h>
2. #include<conio.h>
3. #include<graphics.h>
4. #include<dos.h>
5. void flood(int,int,int,int);
6. void main()
7. {
8. intgd=DETECT,gm;
9. initgraph(&gd,&gm,"C:/TURBOC3/bgi");
10. rectangle(50,50,250,250);
11. flood(55,55,10,0);
12. getch();
13. }
14. void flood(intx,inty,intfillColor, intdefaultColor)
15. {
16. if(getpixel(x,y)==defaultColor)
17. {
18. delay(1);
19. putpixel(x,y,fillColor);
20. flood(x+1,y,fillColor,defaultColor);
21. flood(x-1,y,fillColor,defaultColor);
22. flood(x,y+1,fillColor,defaultColor);
23. flood(x,y-1,fillColor,defaultColor);
24. }
25. }
Output:
1. #include<stdio.h>
2. #include<graphics.h>
3. #include<dos.h>
4. #include<conio.h>
5. void floodfill(intx,inty,intold,intnewcol)
6. {
7. int current;
8. current=getpixel(x,y);
9. if(current==old)
10. {
11. delay(5);
12. putpixel(x,y,newcol);
13. floodfill(x+1,y,old,newcol);
14. floodfill(x-1,y,old,newcol);
15. floodfill(x,y+1,old,newcol);
16. floodfill(x,y-1,old,newcol);
17. floodfill(x+1,y+1,old,newcol);
18. floodfill(x-1,y+1,old,newcol);
19. floodfill(x+1,y-1,old,newcol);
20. floodfill(x-1,y-1,old,newcol);
21. }
22. }
23. void main()
24. {
25. intgd=DETECT,gm;
26. initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
27. rectangle(50,50,150,150);
28. floodfill(70,70,0,15);
29. getch();
30. closegraph();
31. }
Output:
Scan Line Polygon Fill Algorithm:
This algorithm lines interior points of a polygon on the scan line and these points are done on or
off according to requirement. The polygon is filled with various colors by coloring various
pixels.
In above figure polygon and a line cutting polygon in shown. First of all, scanning is done.
Scanning is done using raster scanning concept on display device. The beam starts scanning from
the top left corner of the screen and goes toward the bottom right corner as the endpoint. The
algorithms find points of intersection of the line with polygon while moving from left to right
and top to bottom. The various points of intersection are stored in the frame buffer. The
intensities of such points is keep high. Concept of coherence property is used. According to this
property if a pixel is inside the polygon, then its next pixel will be inside the polygon.
2. Unequal Intensity: It deals with unequal appearance of the brightness of different lines. An
inclined line appears less bright as compared to the horizontal and vertical line.
INTRODUCTION TO TRANSFORMATIONS
Transformations
Computer Graphics provide the facility of viewing object from different angles. The architect
can study building from different angles i.e.
1. Front Evaluation
2. Side elevation
3. Top plan
A Cartographer can change the size of charts and topographical maps. So if graphics images are
coded as numbers, the numbers can be stored in memory. These numbers are modified by
mathematical operations called as Transformation.
The purpose of using computers for drawing is to provide facility to user to view the object from
different angles, enlarging or reducing the scale or shape of object called as Transformation.
2. Coordinate Transformation: The object is held stationary while the coordinate system is
transformed relative to the object. This effect is attained through the application of
coordinate transformations.
The movement of an automobile against a scenic background we can simulate this by:
o We can keep the car fixed while moving the background scenery- (Coordinate
Transformation)
Types of Transformations:
1. Translation
2. Scaling
3. Rotating
4. Reflection
5. Shearing
Note: Translation, Scaling, and Rotation are also called as Basic Transformations.
Translation
It is the straight line movement of an object from one position to another is called Translation.
Here the object is positioned from one coordinate location to another.
Translation of point:
To translate a point from coordinate position (x, y) to another (x1 y1), we add algebraically the
translation distances Tx and Ty to original coordinate.
x1=x+Tx
y1=y+Ty
It is used to alter or change the size of objects. The change is done using scaling factors. There
are two scaling factors, i.e. Sx in x direction Sy in y-direction. If the original position is x and y.
Scaling factors are Sx and Sy then the value of coordinates after scaling will be x1 and y1.
If the picture to be enlarged to twice its original size then Sx = Sy =2. If Sxand Sy are not equal
then scaling will occur but it will elongate or distort the picture.
If scaling factors are less than one, then the size of the object will be reduced. If scaling factors
are higher than one, then the size of the object will be enlarged.
If Sxand Syare equal it is also called as Uniform Scaling. If not equal then called as Differential
Scaling. If scaling factors with values less than one will move the object closer to coordinate
origin, while a value higher than one will move coordinate position farther from origin.
Enlargement: If T1= ,If (x1 y1)is original position and T1is translation vector then (x2 y2)
are coordinated after scaling
Reduction: If T1= . If (x1 y1) is original position and T1 is translation vector, then
(x2 y2) are coordinates after scaling
Matrix for Scaling:
Example: Prove that 2D Scaling transformations are commutative i.e, S1 S2=S2 S1.
Rotation:
It is a process of changing the angle of the object. Rotation can be clockwise or anticlockwise.
For rotation, we have to specify the angle of rotation and rotation point. Rotation point is also
called a pivot point. It is print about which object is rotated.
Types of Rotation:
1. Anticlockwise
2. Counterclockwise
The positive value of the pivot point (rotation angle) rotates an object in a counter-clockwise
(anti-clockwise) direction.
The negative value of the pivot point (rotation angle) rotates an object in a clockwise direction.
When the object is rotated, then every point of the object is rotated by the same angle.
Straight Line: Straight Line is rotated by the endpoints with the same angle and redrawing the
line between new endpoints.
Polygon: Polygon is rotated by shifting every vertex using the same rotational angle.
Curved Lines: Curved Lines are rotated by repositioning of all points and drawing of the curve
at new positions.
Ellipse: Its rotation can be obtained by rotating major and minor axis of an ellipse by the desired
angle.
Matrix for rotation is a clockwise direction.
1. #include<stdio.h>
2. #include<graphics.h>
3. #include<math.h>
4. int main()
5. {
6. intgd=0,gm,x1,y1,x2,y2;
7. double s,c, angle;
8. initgraph(&gd, &gm, "C:\\TC\\BGI");
9. setcolor(RED);
10. printf("Enter coordinates of line: ");
11. scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
12. cleardevice();
13. setbkcolor(WHITE);
14. line(x1,y1,x2,y2);
15. getch();
16. setbkcolor(BLACK);
17. printf("Enter rotation angle: ");
18. scanf("%lf", &angle);
19. setbkcolor(WHITE);
20. c = cos(angle *3.14/180);
21. s = sin(angle *3.14/180);
22. x1 = floor(x1 * c + y1 * s);
23. y1 = floor(-x1 * s + y1 * c);
24. x2 = floor(x2 * c + y2 * s);
25. y2 = floor(-x2 * s + y2 * c);
26. cleardevice();
27. line(x1, y1 ,x2, y2);
28. getch();
29. closegraph();
30. return 0;
31. }
Output:
Before rotation
After rotation
Program to rotate a Triangle:
1. #include<stdio.h>
2. #include<graphics.h>
3. #include<math.h>
4. main()
5. {
6. intgd=0,gm,x1,y1,x2,y2,x3,y3;
7. double s,c, angle;
8. initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
9. setcolor(RED);
10. printf("Enter coordinates of triangle: ");
11. scanf("%d%d%d%d%d%d",&x1,&y1,&x2,&y2, &x3, &y3);
12. setbkcolor(WHITE);
13. cleardevice();
14. line(x1,y1,x2,y2);
15. line(x2,y2, x3,y3);
16. line(x3, y3, x1, y1);
17. getch();
18. setbkcolor(BLACK);
19. printf("Enter rotation angle: ");
20. scanf("%lf", &angle);
21. setbkcolor(WHITE);
22. c = cos(angle *M_PI/180);
23. s = sin(angle *M_PI/180);
24. x1 = floor(x1 * c + y1 * s);
25. y1 = floor(-x1 * s + y1 * c);
26. x2 = floor(x2 * c + y2 * s);
27. y2 = floor(-x2 * s + y2 * c);
28. x3 = floor(x3 * c + y3 * s);
29. y3 = floor(-x3 * s + y3 * c);
30. cleardevice();
31. line(x1, y1 ,x2, y2);
32. line(x2,y2, x3,y3);
33. line(x3, y3, x1, y1);
34. getch();
35. closegraph();
36. return 0;
37. }
Output:
Before rotation
After rotation
Reflection:
It is a transformation which produces a mirror image of an object. The mirror image can be either
about x-axis or y-axis. The object is rotated by180°.
Types of Reflection:
3. Reflection about an axis perpendicular to xy plane and passing through the origin
1. Reflection about x-axis: The object can be reflected about x-axis with the help of the
following matrix
In this transformation value of x will remain same whereas the value of y will become negative.
Following figures shows the reflection of the object axis. The object will lie another side of the
x-axis.
2. Reflection about y-axis: The object can be reflected about y-axis with the help of following
transformation matrix
Here the values of x will be reversed, whereas the value of y will remain the same. The object
will lie another side of the y-axis.
In this value of x and y both will be reversed. This is also called as half revolution about the
origin.
4. Reflection about line y=x: The object may be reflected about line y = x with the help of
following transformation matrix
First of all, the object is rotated at 45°. The direction of rotation is clockwise. After it reflection
is done concerning x-axis. The last step is the rotation of y=x back to its original position that is
counterclockwise at 45°.
A (3 4)
B (6 4)
C (4 8)
Solution:
1. #include <iostream.h>
2. #include <conio.h>
3. #include <graphics.h>
4. #include <math.h>
5. #include <stdlib.h>
6. #define pi 3.14
7. class arc
8. {
9. float x[10],y[10],theta,ref[10][10],ang;
10. float p[10][10],p1[10][10],x1[10],y1[10],xm,ym;
11. int i,k,j,n;
12. public:
13. void get();
14. void cal ();
15. void map ();
16. void graph ();
17. void plot ();
18. void plot1();
19. };
20. void arc::get ()
21. {
22. cout<<"\n ENTER ANGLE OF LINE INCLINATION AND Y INTERCEPT";
23. cin>> ang >> b;
24. cout <<"\n ENTER NO OF VERTICES";
25. cin >> n;
26. cout <<"\n ENTER";
27. for (i=0; i<n; i++)
28. {
29. cout<<"\n x["<<i<<"] and y["<<i<<"]";
30. }
31. theta =(ang * pi)/ 180;
32. ref [0] [0] = cos (2 * theta);
33. ref [0] [1] = sin (2 * theta);
34. ref [0] [2] = -b *sin (2 * theta);
35. ref [1] [0] = sin (2 * theta);
36. ref [1] [1] = -cos (2 * theta);
37. ref [1] [2] = b * (cos (2 * theta)+1);
38. ref [2] [0]=0;
39. ref [2] [1]=0;
40. ref [2] [2] = 1;
41. }
42. void arc :: cal ()
43. {
44. for (i=0; i < n; i++)
45. {
46. p[0] [i] = x [i];
47. p [1] [i] = y [i];
48. p [2] [i] = 1;
49. }
50. for (i=0; i<3;i++)
51. {
52. for (j=0; j<n; j++)
53. {
54. p1 [i] [j]=0;
55. for (k=0;k<3; k++)
56. }
57. p1 [i] [j] + = ref [i] [k] * p [k] [j];
58. }
59. for (i=0; i<n; i++)
60. {
61. x1 [i]=p1[0] [i];
62. y1 [i] = p1 [1] [i];
63. }
64. }
65. void arc :: map ()
66. {
67. int gd = DETECT,gm;
68. initgraph (&gd, &gm, " ");
69. int errorcode = graphresult ();
70. /* an error occurred */
71. if (errorcode ! = grOK)
72. {
73. printf ("Graphics error: %s \n", grapherrormsg (errorcode));
74. printf ("Press any key to halt:");
75. getch ();
76. exit (1); /* terminate with an error code */
77. }
78. }
79. void arc :: graph ()
80. {
81. xm=getmaxx ()/2;
82. ym=getmaxy ()/2;
83. line (xm, 0, xmm 2*ym);
84. }
85. void arc :: plot 1 ()
86. {
87. for (i=0; i <n-1; i++)
88. {
89. circle (x1[i]+xm, (-y1[i]+ym), 2);
90. line (x1[i]+xm, (-y1[i]+ym), x1[i+1]+xm, (-y1[i+1]+ym));
91. }
92. line (x1[n-1)+xm, (-y1[n-1]+ym), x1[0]+xm, (-y1[0]+ym));
93. getch();
94. }
95. void arc :: plot ()
96. {
97. for (i=0; i <n-1; i++)
98. {
99. circle (x1[i]+xm, (-y1[i]+ym, 2);
100. line (x1[i]+xm, (-y1[i]+ym), x[i+1]+xm, (-y1[i+1]+ym));
101. }
102. line (x[n-1]+xm, (-y1[n-1]+ym), x[0]+xm, (-y[0]+ym));
103. getch();
104. }
105. void main ()
106. {
107. class arc a;
108. clrscr();
109. a.map();
110. a.graph();
111. a.get();
112. a.cal();
113. a.plot();
114. a.plot1();
115. getch();
116. }
Output:
Shearing:
It is transformation which changes the shape of object. The sliding of layers of object
occur. The shear can be in one direction or in two directions.
Shearing in the X-direction: In this horizontal shearing sliding of layers occur. The
homogeneous matrix for shearing in the x-direction is shown below:
Shearing in the Y-direction: Here shearing is done by sliding along vertical or y-axis.
Output:
Translate
1: TRANSLATION
2: SCALING
3: ROTATION
4: REFLECTION
5: SHEARING
6: EXIT
ENTER YOUR CHOICE 4
REFLECTION MENU
1: X-PLANE
2: Y-PLANE
3: ORIGIN
4: Y=X PLANE
5: Y=-X PLANE
ENTER YOUR CHOICE 4
1: TRANSLATION
2: SCALING
3: ROTATION
4: REFLECTION
5: SHEARING
6: EXIT
ENTER YOUR CHOICE 5
SHEARING MENU
1: X-DIR
2: Y-DIR
ENTER YOUR CHOICE 3
ENTER SHX 5
ENTER SHY 5
ENTER THE NO OF VERTICES
5
ENTER THE 1 COORDINATES
10 10
ENTER THE 2 COORDINATES
30 10
ENTER THE 3 COORDINATES
40 20
ENTER THE 4 COORDINATES
35 30
ENTER THE 5 COORDINATES
15 20
1: TRANSLATION
2: SCALING
3: ROTATION
4: REFLECTION
5: SHEARING
6: EXIT
ENTER YOUR CHOICE 1
ENTER TX AND TY 10 10
Homogeneous Coordinates
The rotation of a point, straight line or an entire image on the screen, about a point
other than origin, is achieved by first moving the image until the point of rotation
occupies the origin, then performing rotation, then finally moving the image to its
original position.
The moving of an image from one place to another in a straight line is called a
translation. A translation may be done by adding or subtracting to each point, the
amount, by which picture is required to be shifted.
Suppose we want to perform rotation about an arbitrary point, then we can perform it
by the sequence of three transformations
1. Translation
2. Rotation
3. Reverse Translation
Step2: The object is translated so that its center coincides with the origin as in fig (b)
Above resultant matrix show that two successive translations are additive.
1. Translate object to origin from its original position as shown in fig (b)
2. Rotate the object about the origin as shown in fig (c).
3. Translate the object to its original position from origin. It is called as reverse translation
as shown in fig (d).
The matrix multiplication of above 3 steps is given below
Step2: The object is translated so that its center coincides with origin as shown in fig (b)