Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore computer_graphics_tutorial

computer_graphics_tutorial

Published by ajaysingh97811, 2017-07-31 07:50:31

Description: computer_graphics_tutorial

Search

Read the Text Version

r

Computer GraphicsAbout the TutorialTo display a picture of any size on a computer screen is a difficult process.Computer graphics are used to simplify this process. Various algorithms andtechniques are used to generate graphics in computers. This tutorial will help youunderstand how all these are processed by the computer to give a rich visualexperience to the user.AudienceThis tutorial has been prepared for students who don’t know how graphics areused in computers. It explains the basics of graphics and how they areimplemented in computers to generate various visuals.PrerequisitesBefore you start proceeding with this tutorial, we assume that you are alreadyaware of the basic concepts of C programming language and basic mathematics.Copyright & Disclaimer Copyright 2015 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of TutorialsPoint (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy,distribute or republish any contents or a part of contents of this e-book in anymanner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and asprecisely as possible, however, the contents may contain inaccuracies or errors.Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy,timeliness or completeness of our website or its contents including this tutorial. Ifyou discover any errors on our website or in this tutorial, please notify us [email protected] i

Computer GraphicsTable of Contents About the Tutorial ..................................................................................................................................i Audience ................................................................................................................................................i Prerequisites ..........................................................................................................................................i Copyright & Disclaimer ...........................................................................................................................i Table of Contents ..................................................................................................................................ii1. COMPUTER GRAPHICS – BASICS.........................................................................................1 Cathode Ray Tube .................................................................................................................................1 Raster Scan............................................................................................................................................2 Application of Computer Graphics.........................................................................................................32. LINE GENERATION ALGORITHM .........................................................................................5 DDA Algorithm ......................................................................................................................................5 Bresenham’s Line Generation................................................................................................................6 Mid-Point Algorithm..............................................................................................................................93. CIRCLE GENERATION ALGORITHM ...................................................................................11 Bresenham’s Algorithm .......................................................................................................................11 Mid Point Algorithm ............................................................................................................................134. POLYGON FILLING ............................................................................................................16 Scan Line Algorithm.............................................................................................................................16 Flood Fill Algorithm .............................................................................................................................17 Boundary Fill Algorithm.......................................................................................................................18 4-Connected Polygon...........................................................................................................................18 8-Connected Polygon...........................................................................................................................19 Inside-outside Test ..............................................................................................................................21 ii

Computer Graphics5. VIEWING AND CLIPPING...................................................................................................24 Point Clipping ......................................................................................................................................24 Line Clipping ........................................................................................................................................24 Cohen-Sutherland Line Clippings .........................................................................................................25 Cyrus-Beck Line Clipping Algorithm .....................................................................................................27 Polygon Clipping (Sutherland Hodgman Algorithm).............................................................................28 Text Clipping........................................................................................................................................29 Bitmap Graphics ..................................................................................................................................316. 2D TRANSFORMATION.....................................................................................................33 Homogenous Coordinates ...................................................................................................................33 Translation ..........................................................................................................................................33 Rotation ..............................................................................................................................................34 Scaling .................................................................................................................................................36 Reflection ............................................................................................................................................37 Shear ...................................................................................................................................................38 Composite Transformation..................................................................................................................397. 3D GRAPHICS ...................................................................................................................41 Parallel Projection ...............................................................................................................................41 Orthographic Projection ......................................................................................................................42 Oblique Projection...............................................................................................................................43 Isometric Projections...........................................................................................................................43 Perspective Projection.........................................................................................................................44 Translation ..........................................................................................................................................45 Rotation ..............................................................................................................................................46 Scaling .................................................................................................................................................47 Shear ...................................................................................................................................................48 iii

Computer Graphics Transformation Matrices .....................................................................................................................498. CURVES............................................................................................................................51 Types of Curves ...................................................................................................................................51 Bezier Curves.......................................................................................................................................52 Properties of Bezier Curves..................................................................................................................52 B-Spline Curves....................................................................................................................................53 Properties of B-spline Curve ................................................................................................................549. SURFACES ........................................................................................................................55 Polygon Surfaces .................................................................................................................................55 Polygon Tables ....................................................................................................................................55 Plane Equations...................................................................................................................................57 Polygon Meshes ..................................................................................................................................5710. VISIBLE SURFACE DETECTION...........................................................................................59 Depth Buffer (Z-Buffer) Method ..........................................................................................................59 Scan-Line Method................................................................................................................................61 Area-Subdivision Method ....................................................................................................................61 Back-Face Detection ............................................................................................................................62 A-Buffer Method .................................................................................................................................64 Depth Sorting Method.........................................................................................................................65 Binary Space Partition (BSP) Trees.......................................................................................................6611. FRACTALS.........................................................................................................................68 What are Fractals?...............................................................................................................................68 Generation of Fractals .........................................................................................................................68 Geometric Fractals ..............................................................................................................................6912. COMPUTER ANIMATION ..................................................................................................71 iv

Computer GraphicsAnimation Techniques.........................................................................................................................71Key Framing.........................................................................................................................................72Morphing.............................................................................................................................................73 v

1. COMPUTER GRAPHICS – BASICSComputer GraphicsComputer graphics is an art of drawing pictures on computer screens with the help ofprogramming. It involves computations, creation, and manipulation of data. In otherwords, we can say that computer graphics is a rendering tool for the generation andmanipulation of images.Cathode Ray TubeThe primary output device in a graphical system is the video monitor. The mainelement of a video monitor is the Cathode Ray Tube (CRT), shown in the followingillustration.The operation of CRT is very simple: 1. The electron gun emits a beam of electrons (cathode rays). 2. The electron beam passes through focusing and deflection systems that direct it towards specified positions on the phosphor-coated screen. 3. When the beam hits the screen, the phosphor emits a small spot of light at each position contacted by the electron beam. 4. It redraws the picture by directing the electron beam back over the same screen points quickly.Figure: Cathode Ray Tube 1

Computer GraphicsThere are two ways (Random scan and Raster scan) by which we can display an objecton the screen.Raster ScanIn a raster scan system, the electron beam is swept across the screen, one row at atime from top to bottom. As the electron beam moves across each row, the beamintensity is turned on and off to create a pattern of illuminated spots.Picture definition is stored in memory area called the Refresh Buffer or FrameBuffer. This memory area holds the set of intensity values for all the screen points.Stored intensity values are then retrieved from the refresh buffer and “painted” on thescreen one row (scan line) at a time as shown in the following illustration.Each screen point is referred to as a pixel (picture element) or pel. At the end ofeach scan line, the electron beam returns to the left side of the screen to begindisplaying the next scan line. Figure: Raster ScanRandom Scan (Vector Scan)In this technique, the electron beam is directed only to the part of the screen wherethe picture is to be drawn rather than scanning from left to right and top to bottom asin raster scan. It is also called vector display, stroke-writing display, orcalligraphic display.Picture definition is stored as a set of line-drawing commands in an area of memoryreferred to as the refresh display file. To display a specified picture, the system 2

Computer Graphicscycles through the set of commands in the display file, drawing each component linein turn. After all the line-drawing commands are processed, the system cycles back tothe first line command in the list.Random-scan displays are designed to draw all the component lines of a picture 30 to60 times each second. Figure: Random ScanApplication of Computer GraphicsComputer Graphics has numerous applications, some of which are listed below:  Computer graphics user interfaces (GUIs) – A graphic, mouse-oriented paradigm which allows the user to interact with a computer.  Business presentation graphics - \"A picture is worth a thousand words\".  Cartography - Drawing maps.  Weather Maps – Real-time mapping, symbolic representations.  Satellite Imaging - Geodesic images.  Photo Enhancement - Sharpening blurred photos.  Medical imaging - MRIs, CAT scans, etc. - Non-invasive internal examination. 3

Computer Graphics Engineering drawings - mechanical, electrical, civil, etc. - Replacing the blueprints of the past. Typography - The use of character images in publishing - replacing the hard type of the past. Architecture - Construction plans, exterior sketches - replacing the blueprints and hand drawings of the past. Art - Computers provide a new medium for artists. Training - Flight simulators, computer aided instruction, etc. Entertainment - Movies and games. Simulation and modeling - Replacing physical modeling and enactments 4

2. LINE GENERATION ALGORICToHmpMuter GraphicsA line connects two points. It is a basic element in graphics. To draw a line, you needtwo points between which you can draw a line. In the following three algorithms, werefer the one point of line as X0, Y0 and the second point of line as X1, Y1.DDAAlgorithmDigital Differential Analyzer (DDA) algorithm is the simple line generation algorithmwhich is explained step by step here.Step 1: Get the input of two end points (X0, Y0) and (X1, Y1).Step 2: Calculate the difference between two end points. dx = X1 - X0 dy = Y1 - Y0Step 3: Based on the calculated difference in step-2, you need to identify the numberof steps to put pixel. If dx > dy, then you need more steps in x coordinate; otherwisein y coordinate. if (dx > dy) Steps = absolute(dx); else Steps = absolute(dy);Step 4: Calculate the increment in x coordinate and y coordinate. Xincrement = dx / (float) steps; Yincrement = dy / (float) steps; 5

Computer GraphicsStep 5: Put the pixel by successfully incrementing x and y coordinates accordingly andcomplete the drawing of the line. for(int v=0; v < Steps; v++) { x = x + Xincrement; y = y + Yincrement; putpixel(x,y); }Bresenham’s Line GenerationThe Bresenham algorithm is another incremental scan conversion algorithm. The bigadvantage of this algorithm is that, it uses only integer calculations. Moving across thex axis in unit intervals and at each step choose between two different y coordinates.For example, as shown in the following illustration, from position (2, 3) you need tochoose between (3, 3) and (3, 4). You would like the point that is closer to the originalline.At sample position xk+1, the vertical separations from the mathematical line arelabelled as dupper and dlower. 6

Computer GraphicsFrom the above illustration, the y coordinate on the mathematical line at xk+1 is: ������ = ������(������������ + 1) + ������So, dupper and dlower are given as follows: ������������������������������������ = ������ − ������������ = ������(������������ + 1) + ������ − ������������and ������������������������������������ = (������������ + 1) − ������ = ������������ + 1 − ������(������������ + 1) − ������You can use these to make a simple decision about which pixel is closer to themathematical line. This simple decision is based on the difference between the twopixel positions. ������������������������������������ − ������������������������������������ = 2������(������������ + 1) − 2������������ + 2������ − 1Let us substitute m with dy/dx where dx and dy are the differences between the end-points. ������������(������������������������������������ − ������������������������������������) = ������������(2 ������������ (������������ + 1) − 2������������ + 2������ − 1) ������������ = 2������������ ∙ ������������ − 2������������ ∙ ������������ + 2������������ + ������������(2������ − 1) = 2������������ ∙ ������������ − 2������������ ∙ ������������ + ������So, a decision parameter pk for the kth step along a line is given by: ������������ = ������������(������������������������������������ − ������������������������������������) = 2������������ ∙ ������������ − 2������������ ∙ ������������ + ������The sign of the decision parameter pk is the same as that of dlower – dupper. 7

Computer GraphicsIf pk is negative, then choose the lower pixel, otherwise choose the upper pixel.Remember, the coordinate changes occur along the x axis in unit steps, so you can doeverything with integer calculations. At step k+1, the decision parameter is given as: ������������+1 = 2������������ ∙ ������������+1 − 2������������ ∙ ������������+1 + ������Subtracting pk from this we get: ������������+1 − ������������ = 2������������(������������+1 − ������������) − 2������������(������������+1 − ������������)But, xk+1 is the same as xk+1. So: ������������+1 = ������������ + 2������������ − 2������������(������������+1 − ������������)Where, yk+1 – yk is either 0 or 1 depending on the sign of pk.The first decision parameter p0 is evaluated at (x0, y0) is given as: ������0 = 2������������ − ������������Now, keeping in mind all the above points and calculations, here is the Bresenhamalgorithm for slope m < 1:Step 1: Input the two end-points of line, storing the left end-point in (x0, y0).Step 2: Plot the point (x0, y0).Step 3: Calculate the constants dx, dy, 2dy, and (2dy – 2dx) and get the first valuefor the decision parameter as: ������0 = 2������������ − ������������Step 4: At each xk along the line, starting at k = 0, perform the following test:If pk < 0, the next point to plot is (xk+1, yk) and ������������+1 = ������������ + 2������������Otherwise, ������������+1 = ������������ + 2������������ − 2������������Step 5: Repeat step 4 (dx – 1) times.For m > 1, find out whether you need to increment x while incrementing y each time.After solving, the equation for decision parameter pk will be very similar, just the xand y in the equation gets interchanged. 8

Computer GraphicsMid-Point AlgorithmMid-point algorithm is due to Bresenham which was modified by Pitteway and VanAken. Assume that you have already put the point P at (x, y) coordinate and the slopeof the line is 0 ≤ k ≤ 1 as shown in the following illustration.Now you need to decide whether to put the next point at E or N. This can be chosenby identifying the intersection point Q closest to the point N or E. If the intersectionpoint Q is closest to the point N then N is considered as the next point; otherwise E. Figure: Mid-point AlgorithmTo determine that, first calculate the mid-point M(x+1, y + ½). If the intersection pointQ of the line with the vertical line connecting E and N is below M, then take E as thenext point; otherwise take N as the next point.In order to check this, we need to consider the implicit equation: F(x,y) = mx + b - yFor positive m at any given X,  If y is on the line, then F(x, y) = 0  If y is above the line, then F(x, y) < 0  If y is below the line, then F(x, y) > 0 9

Computer Graphics 10

3. CIRCLE GENERATION ALGORITHMComputer GraphicsDrawing a circle on the screen is a little complex than drawing a line. There are twopopular algorithms for generating a circle: Bresenham’s Algorithm and MidpointCircle Algorithm. These algorithms are based on the idea of determining thesubsequent points required to draw the circle. Let us discuss the algorithms in detail:The equation of circle is X2 + Y2 = r2, where r is radius. (-b,a) (b,a) (-a,b) (a,b)(-a,-b) (a,-b) (-b,-a) (b,-a)Bresenham’s AlgorithmWe cannot display a continuous arc on the raster display. Instead, we have to choosethe nearest pixel position to complete the arc.From the following illustration, you can see that we have put the pixel at (X, Y) locationand now need to decide where to put the next pixel: at N (X+1, Y) or at S (X+1, Y-1). 11

Computer GraphicsThis can be decided by the decision parameter d.  If d <= 0, then N(X+1, Y) is to be chosen as next pixel.  If d > 0, then S(X+1, Y-1) is to be chosen as the next pixel.AlgorithmStep 1: Get the coordinates of the center of the circle and radius, and store them inx, y, and R respectively. Set P=0 and Q=R.Step 2: Set decision parameter D = 3 – 2R.Step 3: Repeat through step-8 while X < Y.Step 4: Call Draw Circle (X, Y, P, Q).Step 5: Increment the value of P.Step 6: If D < 0 then D = D + 4x + 6.Step 7: Else Set Y = Y + 1, D = D + 4(X-Y) + 10.Step 8: Call Draw Circle (X, Y, P, Q). Draw Circle Method(X, Y, P, Q). Call Putpixel (X + P, Y + Q). Call Putpixel (X - P, Y + Q). Call Putpixel (X + P, Y - Q). Call Putpixel (X - P, Y - Q). Call Putpixel (X + Q, Y + X). 12

Computer Graphics Call Putpixel (X - Q, Y + X). Call Putpixel (X + Q, Y - X). Call Putpixel (X - Q, Y - X).Mid Point AlgorithmStep 1: Input radius r and circle center (xc, yc) and obtain the first point on thecircumference of the circle centered on the origin as (x0, y0) = (0, r)Step 2: Calculate the initial value of decision parameter asP0 = 5/4 – r (See the following description for simplification of this equation.) f(x, y) = x2 + y2 - r2 = 0 f(xi - 1/2 + e, yi + 1) = (xi - 1/2 + e)2 + (yi + 1)2 - r2 = (xi- 1/2)2 + (yi + 1)2 - r2 + 2(xi - 1/2)e + e2 = f(xi - 1/2, yi + 1) + 2(xi - 1/2)e + e2 = 0 13

Computer GraphicsLet di = f(xi - 1/2, yi + 1) = -2(xi - 1/2)e - e2Thus,If e < 0 then di > 0 so choose point S = (xi - 1, yi + 1).di+1 = f(xi – 1 - 1/2, yi + 1 + 1) = ((xi - 1/2) - 1)2 + ((yi + 1) + 1)2 - r2 = di - 2(xi - 1) + 2(yi + 1) + 1 = di + 2(yi+1 - xi+1) + 1If e >= 0 then di <= 0 so choose point T = (xi, yi + 1) di+1 = f(xi - 1/2, yi + 1 + 1) = di + 2yi+1 + 1The initial value of di is d0 = f(r - 1/2, 0 + 1) = (r - 1/2)2 + 12 - r2 = 5/4 - r {1 - r can be used if r is an integer}When point S = (xi - 1, yi + 1) is chosen, then 14

Computer Graphics di+1 = di + 2xi+1 + 2yi+1 + 1When point T = (xi, yi + 1) is chosen then di+1 = di + 2yi+1 + 1Step 3: At each XK position starting at K=0, perform the following test: If PK < 0 then next point on circle (0,0) is (XK+1,YK) and PK+1 = PK + 2XK+1 + 1 Else PK+1 = PK + 2XK+1 + 1 – 2YK+1 Where, 2XK+1 = 2XK+2 and 2YK+1 = 2YK-2.Step 4: Determine the symmetry points in other seven octants.Step 5: Move each calculate pixel position (X, Y) onto the circular path centered on(XC, YC) and plot the coordinate values.X = X + XC, Y = Y + YCStep 6: Repeat step-3 through 5 until X >= Y. 15

4. POLYGON FILLING Computer GraphicsPolygon is an ordered list of vertices as shown in the following figure. For fillingpolygons with particular colors, you need to determine the pixels falling on the borderof the polygon and those which fall inside the polygon. In this chapter, we will see howwe can fill polygons using different techniques. Figure: A PolygonScan Line AlgorithmThis algorithm works by intersecting scanline with polygon edges and fills the polygonbetween pairs of intersections. The following steps depict how this algorithm works.Step 1: Find out the Ymin and Ymax from the given polygon. ScanLineStep 2: ScanLine intersects with each edge of the polygon from Ymin to Ymax. Nameeach intersection point of the polygon. As per the figure shown above, they are namedas p0, p1, p2, p3. 16

Computer GraphicsStep 3: Sort the intersection point in the increasing order of X coordinate i.e. (p0, p1),(p1, p2), and (p2, p3).Step 4: Fill all those pair of coordinates that are inside polygons and ignore thealternate pairs.Flood Fill AlgorithmSometimes we come across an object where we want to fill the area and its boundarywith different colors. We can paint such objects with a specified interior color insteadof searching for particular boundary color as in boundary filling algorithm.Instead of relying on the boundary of the object, it relies on the fill color. In otherwords, it replaces the interior color of the object with the fill color. When no more pixelsof the original interior color exist, the algorithm is completed.Once again, this algorithm relies on the Four-connect or Eight-connect method of fillingin the pixels. But instead of looking for the boundary color, it is looking for all adjacentpixels that are a part of the interior. 17

Computer GraphicsBoundary Fill AlgorithmThe boundary fill algorithm works as its name. This algorithm picks a point inside anobject and starts to fill until it hits the boundary of the object. The color of the boundaryand the color that we fill should be different for this algorithm to work.In this algorithm, we assume that color of the boundary is same for the entire object.The boundary fill algorithm can be implemented by 4-connetected pixels or 8-connected pixels.4-Connected PolygonIn this technique 4-connected pixels are used as shown in the figure. We are puttingthe pixels above, below, to the right, and to the left side of the current pixels and thisprocess will continue until we find a boundary with different color.AlgorithmStep 1: Initialize the value of seed point (seedx, seedy), fcolor and dcol.Step 2: Define the boundary values of the polygon.Step 3: Check if the current seed point is of default color, then repeat the steps 4 and5 till the boundary pixels reached. If getpixel(x, y) = dcol then repeat step 4 and 5Step 4: Change the default color with the fill color at the seed point. setPixel(seedx, seedy, fcol) 18

Computer GraphicsStep 5: Recursively follow the procedure with four neighborhood points. FloodFill (seedx – 1, seedy, fcol, dcol) FloodFill (seedx + 1, seedy, fcol, dcol) FloodFill (seedx, seedy - 1, fcol, dcol) FloodFill (seedx – 1, seedy + 1, fcol, dcol)Step 6: ExitThere is a problem with this technique. Consider the case as shown below where wetried to fill the entire region. Here, the image is filled only partially. In such cases, 4-connected pixels technique cannot be used.8-Connected PolygonIn this technique, 8-connected pixels are used as shown in the figure. We are puttingpixels above, below, right and left side of the current pixels as we were doing in 4-connected technique.In addition to this, we are also putting pixels in diagonals so that entire area of thecurrent pixel is covered. This process will continue until we find a boundary withdifferent color. 19

Computer GraphicsAlgorithmStep 1: Initialize the value of seed point (seedx, seedy), fcolor and dcol.Step 2: Define the boundary values of the polygon.Step 3: Check if the current seed point is of default color then repeat the steps 4 and5 till the boundary pixels reached If getpixel(x,y) = dcol then repeat step 4 and 5Step 4: Change the default color with the fill color at the seed point. setPixel(seedx, seedy, fcol)Step 5: Recursively follow the procedure with four neighbourhood points. FloodFill (seedx – 1, seedy, fcol, dcol) FloodFill (seedx + 1, seedy, fcol, dcol) FloodFill (seedx, seedy - 1, fcol, dcol) FloodFill (seedx, seedy + 1, fcol, dcol) FloodFill (seedx – 1, seedy + 1, fcol, dcol) FloodFill (seedx + 1, seedy + 1, fcol, dcol) FloodFill (seedx + 1, seedy - 1, fcol, dcol) 20

Computer Graphics FloodFill (seedx – 1, seedy - 1, fcol, dcol)Step 6: ExitThe 4-connected pixel technique failed to fill the area as marked in the following figurewhich won’t happen with the 8-connected technique.Inside-outside TestThis method is also known as counting number method. While filling an object, weoften need to identify whether particular point is inside the object or outside it. Thereare two methods by which we can identify whether particular point is inside an objector outside.  Odd-Even Rule  Nonzero winding number ruleOdd-Even RuleIn this technique, we will count the edge crossing along the line from any point (x,y)to infinity. If the number of interactions is odd, then the point (x,y) is an interior point;and if the number of interactions is even, then the point (x,y) is an exterior point. Thefollowing example depicts this concept. 21

Computer Graphics (x, y)From the above figure, we can see that from the point (x,y), the number of interactionspoint on the left side is 5 and on the right side is 3. From both ends, the number ofinteraction points is odd, so the point is considered within the object.Nonzero Winding Number RuleThis method is also used with the simple polygons to test the given point is interior ornot. It can be simply understood with the help of a pin and a rubber band. Fix up thepin on one of the edge of the polygon and tie-up the rubber band in it and then stretchthe rubber band along the edges of the polygon.When all the edges of the polygon are covered by the rubber band, check out the pinwhich has been fixed up at the point to be test. If we find at least one wind at the pointconsider it within the polygon, else we can say that the point is not inside the polygon.In another alternative method, give directions to all the edges of the polygon. Draw ascan line from the point to be test towards the left most of X direction. 22

Computer Graphics Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values. Check the edge direction values from which the scan line is passing and sum up them. If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point. In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point. 23

5. VIEWING AND CLIPPINGComputer GraphicsThe primary use of clipping in computer graphics is to remove objects, lines, or linesegments that are outside the viewing pane. The viewing transformation is insensitiveto the position of points relative to the viewing volume – especially those points behindthe viewer – and it is necessary to remove these points before generating the view.Point ClippingClipping a point from a given window is very easy. Consider the following figure, wherethe rectangle indicates the window. Point clipping tells us whether the given point (X,Y) is within the given window or not; and decides whether we will use the minimumand maximum coordinates of the window.The X-coordinate of the given point is inside the window, if X lies in between Wx1 ≤ X≤ Wx2. Same way, Y coordinate of the given point is inside the window, if Y lies inbetween Wy1 ≤ Y ≤ Wy2.Line ClippingThe concept of line clipping is same as point clipping. In line clipping, we will cut theportion of line which is outside of window and keep only the portion that is inside thewindow. 24

Computer GraphicsCohen-Sutherland Line ClippingsThis algorithm uses the clipping window as shown in the following figure. The minimumcoordinate for the clipping region is (XWmin, YWmin) and the maximum coordinate forthe clipping region is (XWmax, YWmax).We will use 4-bits to divide the entire region. These 4 bits represent the Top, Bottom,Right, and Left of the region as shown in the following figure. Here, the TOP and LEFTbit is set to 1 because it is the TOP-LEFT corner. 25

Computer GraphicsThere are 3 possibilities for the line: 1. Line can be completely inside the window (This line should be accepted). 2. Line can be completely outside of the window (This line will be completely removed from the region). 3. Line can be partially inside the window (We will find intersection point and draw only that portion of line that is inside region).AlgorithmStep 1: Assign a region code for each endpoints.Step 2: If both endpoints have a region code 0000 then accept this line.Step 3: Else, perform the logical AND operation for both region codes. Step 3.1: If the result is not 0000, then reject the line.Step 3.2: Else you need clipping. Step 3.2.1: Choose an endpoint of the line that is outside the window. Step 3.2.2: Find the intersection point at the window boundary (base on region code). Step 3.2.3: Replace endpoint with the intersection point and update the region code. Step 3.2.4: Repeat step 2 until we find a clipped line either trivially accepted or trivially rejected.Step-4: Repeat step 1 for other lines. 26

Computer GraphicsCyrus-Beck Line Clipping AlgorithmThis algorithm is more efficient than Cohen-Sutherland algorithm. It employsparametric line representation and simple dot products.Parametric equation of line is: P0P1:P(t) = P0 + t(P1 - P0)Let Ni be the outward normal edge Ei. Now pick any arbitrary point PEi on edge Ei thenthe dot product Ni∙[P(t) – PEi] determines whether the point P(t) is “inside the clip edge”or “outside” the clip edge or “on” the clip edge.The point P(t) is inside if Ni∙[P(t) – PEi] < 0The point P(t) is outside if Ni∙[P(t) – PEi] > 0The point P(t) is on the edge if Ni∙[P(t) – PEi] = 0 (Intersection point)Ni∙[P(t) – PEi] =0Ni∙[ P0 + t(P1 - P0) – PEi] = 0 (Replacing P(t) with P0 + t(P1 - P0))Ni∙[P0 – PEi] + Ni∙t[P1 - P0] = 0Ni∙[P0 – PEi] + Ni∙tD = 0 (substituting D for [P1 - P0])Ni∙[P0 – PEi] = - Ni ∙ tD 27

Computer GraphicsThe equation for t becomes, t= N������ ∙ [P0 – PEi] −N������ ∙ DIt is valid for the following conditions: 1. Ni ≠ 0 (error cannot happen) 2. D ≠ 0 (P1 ≠ P0) 3. Ni∙D ≠ 0 (P0P1 not parallel to Ei)Polygon Clipping (Sutherland Hodgman Algorithm)A polygon can also be clipped by specifying the clipping window. Sutherland Hodgemanpolygon clipping algorithm is used for polygon clipping. In this algorithm, all thevertices of the polygon are clipped against each edge of the clipping window.First the polygon is clipped against the left edge of the polygon window to get newvertices of the polygon. These new vertices are used to clip the polygon against rightedge, top edge, bottom edge, of the clipping window as shown in the following figure. Figure: Polygon before FillingWhile processing an edge of a polygon with clipping window, an intersection point isfound if edge is not completely inside clipping window and the a partial edge from theintersection point to the outside edge is clipped. The following figures show left, right,top and bottom edge clippings: 28

Computer GraphicsFigure: Clipping Left Edge Figure: Clipping Right EdgeFigure: Clipping Top Edge Figure: Clipping Bottom EdgeText ClippingVarious techniques are used to provide text clipping in a computer graphics. It dependson the methods used to generate characters and the requirements of a particularapplication. There are three methods for text clipping which are listed below: 1. All or none string clipping 2. All or none character clipping 3. Text clipping 29

Computer GraphicsThe following figure shows all or none string clipping:In all or none string clipping method, either we keep the entire string or we rejectentire string based on the clipping window. As shown in the above figure, STRING2 isentirely inside the clipping window so we keep it and STRING1 being only partiallyinside the window, we reject.The following figure shows all or none character clipping:This clipping method is based on characters rather than entire string. In this method ifthe string is entirely inside the clipping window, then we keep it. If it is partially outsidethe window, then:  You reject only the portion of the string being outside  If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string. 30

Computer GraphicsThe following figure shows text clipping:This clipping method is based on characters rather than the entire string. In thismethod if the string is entirely inside the clipping window, then we keep it. If it ispartially outside the window, then  You reject only the portion of string being outside.  If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window.Bitmap GraphicsA bitmap is a collection of pixels that describes an image. It is a type of computergraphics that the computer uses to store and display pictures. In this type of graphics,images are stored bit by bit and hence it is named Bit-map graphics. For betterunderstanding let us consider the following example where we draw a smiley face usingbit-map graphics.Figure: Original Smiley face 31

Computer GraphicsNow we will see how this smiley face is stored bit by bit in computer graphics. Figure: Bitmap storage of smiley faceBy observing the original smiley face closely, we can see that there are two blue lineswhich are represented as B1, B2 and E1, E2 in the above figure.In the same way, the smiley is represented using the combination bits of A4, B5, C6,D6, E5, and F4 respectively.The main disadvantages of bitmap graphics are:  We cannot resize the bitmap image. If you try to resize, the pixels get blurred.  Colored bitmaps can be very large. 32

6. 2D TRANSFORMATIONComputer GraphicsTransformation means changing some graphics into something else by applying rules.We can have various types of transformations such as translation, scaling up or down,rotation, shearing, etc. When a transformation takes place on a 2D plane, it is called2D transformation.Transformations play an important role in computer graphics to reposition the graphicson the screen and change their size or orientation.Homogenous CoordinatesTo perform a sequence of transformation such as translation followed by rotation andscaling, we need to follow a sequential process: 1. Translate the coordinates, 2. Rotate the translated coordinates, and then 3. Scale the rotated coordinates to complete the composite transformation.To shorten this process, we have to use 3×3 transformation matrix instead of 2×2transformation matrix. To convert a 2×2 matrix to 3×3 matrix, we have to add anextra dummy coordinate W.In this way, we can represent the point by 3 numbers instead of 2 numbers, which iscalled Homogenous Coordinate system. In this system, we can represent all thetransformation equations in matrix multiplication. Any Cartesian point P(X, Y) can beconverted to homogenous coordinates by P’ (Xh, Yh, h).TranslationA translation moves an object to a different position on the screen. You can translatea point in 2D by adding translation coordinate (tx, ty) to the original coordinate (X, Y)to get the new coordinate (X’, Y’). 33

Computer GraphicsFrom the above figure, you can write that: X’ = X + tx Y’ = Y + tyThe pair (tx, ty) is called the translation vector or shift vector. The above equationscan also be represented using the column vectors. ������ = [������������] ������′ = [������′] [ ]������������ ������′ ������ = ������������We can write it as: P’ = P + TRotationIn rotation, we rotate the object at particular angle θ (theta) from its origin. From thefollowing figure, we can see that the point P(X, Y) is located at angle Φ from thehorizontal X coordinate with distance r from the origin.Let us suppose you want to rotate it at the angle θ. After rotating it to a new location,you will get a new point P’ (X’, Y’). 34

Computer GraphicsUsing standard trigonometric the original coordinate of point P(X, Y) can berepresented as: X = r cos Φ …….. (1) Y = r sin Φ ……… (2)Same way we can represent the point P’ (X’, Y’) as:X’ = r cos (Φ + θ) = r cos Φ cos θ – r sin Φ sin θ …… (3)Y’ = r sin (Φ + θ) = r cos Φ sin θ + r sin Φ cos θ …… (4)Substituting equation (1) & (2) in (3) & (4) respectively, we will getX’ = X cos θ – Y sin θY’ = X sin θ + Y cos θRepresenting the above equation in matrix form, [������′ ������′] = [������ ������] [−cosisnθθ csoinsθθ]OR P’ = P ∙ RWhere R is the rotation matrix ������ = [−cosisnθθ sin θθ] cosThe rotation angle can be positive and negative. 35

Computer GraphicsFor positive rotation angle, we can use the above rotation matrix. However, fornegative angle rotation, the matrix will change as shown below: ������ = [−cosisn((−−θθ)) csoins((−−θθ))] = [csoins θ −cosisnθθ] (∵ cos(−θ) = cos θ and sin(−θ) = − sin θ) θScalingTo change the size of an object, scaling transformation is used. In the scaling process,you either expand or compress the dimensions of the object. Scaling can be achievedby multiplying the original coordinates of the object with the scaling factor to get thedesired result.Let us assume that the original coordinates are (X, Y), the scaling factors are (SX, SY),and the produced coordinates are (X’, Y’). This can be mathematically represented asshown below: X’ = X ∙ SX and Y’ = Y ∙ SYThe scaling factor SX, SY scales the object in X and Y direction respectively. The aboveequations can also be represented in matrix form as below: [������������′′] = [������������] [���0��������� 0 ������������]OR P’ = P ∙ SWhere S is the scaling matrix. The scaling process is shown in the following figure. Figure: Before scaling process 36

Computer Graphics Figure: After Scaling ProcessIf we provide values less than 1 to the scaling factor S, then we can reduce the size ofthe object. If we provide values greater than 1, then we can increase the size of theobject.ReflectionReflection is the mirror image of original object. In other words, we can say that it isa rotation operation with 180˚. In reflection transformation, the size of the object doesnot change.The following figures show reflections with respect to X and Y axes, and about theorigin respectively. 37

Computer Graphics Figure: Reflection about line y=xShearA transformation that slants the shape of an object is called the shear transformation.There are two shear transformations X-Shear and Y-Shear. One shifts X coordinatesvalues and other shifts Y coordinate values. However, in both the cases, only onecoordinate changes its coordinates and other preserves its values. Shearing is alsotermed as Skewing.X-ShearThe X-Shear preserves the Y coordinate and changes are made to X coordinates, whichcauses the vertical lines to tilt right or left as shown in below figure. 38

Computer GraphicsThe transformation matrix for X-Shear can be represented as: 1 00 ������������ℎ = [Sh������ 1 0] 0 01 X’ = X + Shx ∙ Y Y’ = YY-ShearThe Y-Shear preserves the X coordinates and changes the Y coordinates which causesthe horizontal lines to transform into lines which slopes up or down as shown in thefollowing figure.The Y-Shear can be represented in matrix from as: 1 Sh������ 0 ������������ℎ = [0 1 0] 001 Y’ = Y + Shy ∙ X X’ = XComposite TransformationIf a transformation of the plane T1 is followed by a second plane transformation T2,then the result itself may be represented by a single transformation T which is thecomposition of T1 and T2 taken in that order. This is written as T = T1∙T2.Composite transformation can be achieved by concatenation of transformationmatrices to obtain a combined transformation matrix. 39

Computer GraphicsA combined matrix: [T][X] = [X] [T1] [T2] [T3] [T4] …. [Tn]Where [Ti] is any combination of  Translation  Scaling  Shearing  Rotation  ReflectionThe change in the order of transformation would lead to different results, as in generalmatrix multiplication is not cumulative, that is [A] ∙ [B] ≠ [B] ∙ [A] and the order ofmultiplication. The basic purpose of composing transformations is to gain efficiency byapplying a single composed transformation to a point, rather than applying a series oftransformation, one after another.For example, to rotate an object about an arbitrary point (Xp, Yp), we have to carryout three steps: 1. Translate point (Xp, Yp) to the origin. 2. Rotate it about the origin. 3. Finally, translate the center of rotation back where it belonged. 40

7. 3D GRAPHICS Computer GraphicsIn the 2D system, we use only two coordinates X and Y but in 3D, an extra coordinateZ is added. 3D graphics techniques and their application are fundamental to theentertainment, games, and computer-aided design industries. It is a continuing areaof research in scientific visualization.Furthermore, 3D graphics components are now a part of almost every personalcomputer and, although traditionally intended for graphics-intensive software such asgames, they are increasingly being used by other applications.Parallel ProjectionParallel projection discards z-coordinate and parallel lines from each vertex on theobject are extended until they intersect the view plane. In parallel projection, wespecify a direction of projection instead of center of projection.In parallel projection, the distance from the center of projection to project plane isinfinite. In this type of projection, we connect the projected vertices by line segmentswhich correspond to connections on the original object.Parallel projections are less realistic, but they are good for exact measurements. Inthis type of projections, parallel lines remain parallel and angles are not preserved.Various types of parallel projections are shown in the following hierarchy. 41

Computer Graphics Top Orthographic Front Side Parallel AxonometricProjection Oblique Cavalier Cabinet Figure: Types of Parallel ProjectionOrthographic ProjectionIn orthographic projection the direction of projection is normal to the projection of theplane. There are three types of orthographic projections:  Front Projection  Top Projection  Side Projection 42

Computer GraphicsOblique ProjectionIn orthographic projection, the direction of projection is not normal to the projectionof plane. In oblique projection, we can view the object better than orthographicprojection.There are two types of oblique projections: Cavalier and Cabinet. The Cavalierprojection makes 45˚ angle with the projection plane. The projection of a lineperpendicular to the view plane has the same length as the line itself in Cavalierprojection. In a cavalier projection, the foreshortening factors for all three principaldirections are equal.The Cabinet projection makes 63.4˚ angle with the projection plane. In Cabinetprojection, lines perpendicular to the viewing surface are projected at ½ their actuallength. Both the projections are shown in the following figure: Figure: Cavalier & Cabinet ProjectionIsometric ProjectionsOrthographic projections that show more than one side of an object are calledaxonometric orthographic projections. The most common axonometric projectionis an isometric projection where the projection plane intersects each coordinate axisin the model coordinate system at an equal distance. In this projection parallelism oflines are preserved but angles are not preserved. The following figure shows isometricprojection: 43

Computer Graphics Figure: Isometric ProjectionPerspective ProjectionIn perspective projection, the distance from the center of projection to project plane isfinite and the size of the object varies inversely with distance which looks morerealistic.The distance and angles are not preserved and parallel lines do not remain parallel.Instead, they all converge at a single point called center of projection or projectionreference point. There are 3 types of perspective projections which are shown in thefollowing chart.  One point perspective projection is simple to draw.  Two point perspective projection gives better impression of depth.  Three point perspective projection is most difficult to draw. 44


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook