CS602 Computer Graphics PDF Handouts Virtual University
CS602 Computer Graphics PDF Handouts Virtual University
VU
Computer Graphics
CS602
VU
Table of Contents
Lecture No.1 Lecture No.2 Lecture No.3 Lecture No.4 Lecture No.5 Lecture No.6 Lecture No.7 Lecture No.8 Lecture No.9 Lecture No.10 Lecture No.11 Lecture No.12 Lecture No.13 Lecture No.14 Lecture No.15 Lecture No.16 Lecture No.17 Lecture No.18 Lecture No.19 Lecture No.20 Lecture No.21 Lecture No.22 Lecture No.23 Lecture No.24 Lecture No.25 Lecture No.26 Lecture No.27 Lecture No.28 Lecture No.29 Lecture No.30 Lecture No.31 Lecture No.32 Lecture No.33 Lecture No.34 Lecture No.35 Lecture No.36 Lecture No.37 Lecture No.38 Lecture No.39 Lecture No.40 Lecture No.41 Lecture No.42 Lecture No.43 Lecture No.44 Lecture No.45 Introduction to Computer Graphics....................................................3 Graphics Systems I ..............................................................................25 Graphics Systems II ............................................................................34 Point ......................................................................................................43 Line Drawing Techniques ...................................................................53 Circle Drawing Techniques ................................................................59 Ellipse and Other Curves....................................................................64 Filled-Area Primitives-I ......................................................................78 Filled-Area Primitives-II ....................................................................97 Mathematics Fundamentals .............................................................101 2D Transformations I ........................................................................113 2D Transformations II ......................................................................117 Drawing Example ..............................................................................126 Clipping-I ...........................................................................................136 Clipping-II ..........................................................................................141 3D Concepts .......................................................................................152 3D Transformations I ........................................................................168 3D Transformations II ......................................................................175 Projections ..........................................................................................188 Perspective Projection .......................................................................195 Triangles and Planes .........................................................................203 Triangle Rasterization ......................................................................211 Lighting I ............................................................................................222 Lighting II ..........................................................................................229 Mathematics of Lighting and Shading Part I .................................234 Mathematics of Lighting and Shading Part II Light Types and Shading Models..................................................................................238 Review II ............................................................................................242 Review III ...........................................................................................261 Mathematics of Lighting and Shading Part III ..............................276 Mathematics of Lighting and Shading Part IV ..............................285 Mathematics of Lighting and Shading Part V ................................291 Introduction to OpenGL ...................................................................296 OpenGL Programming - I ................................................................303 OpenGL Programming - II ..............................................................309 Curves .................................................................................................320 Space Curves ......................................................................................326 The Tangent Vector...........................................................................329 Bezier Curves .....................................................................................333 Building Polygonal Models of Surfaces ...........................................340 Fractals ...............................................................................................347 Viewing ...............................................................................................366 Examples of Composing Several Transformations ........................387 Real-World and OpenGL Lighting..................................................393 Evaluators, curves and Surfaces ......................................................413 Animations .........................................................................................423 2 Copyright Virtual University of Pakistan
VU
Lecture No.1
1.1 Definition
Computers accept process, transform and present information. Computer Graphics involves technology to accept, process, transform and present information in a visual form that also concerns with producing images (or animations) using a computer. 1.2 Why Study Computer Graphics? There are certain important reasons to study computer graphics. We will discuss them under certain heads: Visualization I like to see what I am doing. Many a times it happens that you perform certain tasks which you cannot visualize; for example as a student of data structures, you implement trees, graphs and other Abstract Data Types (ADTs) but you cannot visualize them whereas you must be having an inner quest to see what these actually look like. I like to show people what I am doing. Similarly at certain times you would be performing certain tasks which you know but it would be difficult for others to understand them so there is very important requirement of showing the things in order to make them understandable. Graphics is interesting We are visual creatures and for us a picture is worth a thousand words. If we can get rid of text based static screen and get some graphics; its always interesting to see things in colours and motion on the screen. Therefore graphics is interesting because it involves simulation, algorithm, and architecture. Requirement Well there are certain areas which require use of computer graphics heavily. One example is drawing of machines. It is required to prepare drawing of a machine before the actual production. The other heavy requirement is for architects as they have to prepare a complete blue print of the building they have to build long before the actual construction work gets underway. AutoCAD and other applications of the kind are heavily used today for building architecture. Entertainment Merely a couple of decades back, the idea of a 24 hours Cartoons Network was really a far fetched one. That was the time when one would wait for a whole week long before getting an entertainment of mere 15 minutes. Well thanks to computer graphics that have enabled us to entertain ourselves with animated movies, cartoons etc.
VU
1.3 Some History The term computer graphics was coined in 1960 by William Fetter to describe the new design methods that he was developing at Boeing. He created a series of widely reproduced images on a plotter exploring cockpit design using a 3D model of a human body.
Whirlwind: early graphics using Vector Scope (1951) Spacewars: first computer graphics game (MIT 1961)
VU
VU
First ray traced image (Whitted 1980) 1.4 Graphics Applications Due to rapid growth in the field of computing, now computer is used as an economical and efficient tool for the production of pictures. Computer graphics applications are found in almost all areas. Here we will discuss some of the important areas including: i. User Interfaces ii. Layout and Design iii. Scientific Visualization and Analysis iv. Art and Design v. Medicine and Virtual Surgery vi. Layout Design & Architectural Simulations vii. History and cultural heritage viii. Entertainment ix. Simulations x. Games 6 Copyright Virtual University of Pakistan
VU
User Interfaces Almost all the software packages provide a graphical interface. A major component of graphical interface is a window manager that allows a user to display multiple windows like areas on the screen at the same time. Each window can contain a different process that can contain graphical or non-graphical display. In order to make a particular window active, we simply have to click in that window using an interactive pointing device. Graphical Interface also includes menus and icons for fast selection of programs, processing operations or parameter values. An icon is a graphical symbol that is designed to look like the processing option it represents.
VU
3D Studio MAX
VU
Scientific Visualization and Analysis Computer graphics is very helpful in producing graphical representations for scientific visualization and analysis especially in the field of engineering and medicine. It helps a lot in drawing charts and creating models.
VU
ART AND DESIGN Computer graphics is widely used in Fine Arts as well as commercial arts for producing better as well as cost effective pictures. Artists use a variety of programs in their work, provided by computer graphics. Some of the most frequently used packages include: Artists paintbrush Pixel paint Super paint
VU
Medicine and Virtual Surgery Computer graphics has extensive use in tomography and simulations of operations. Tomography is the technique that allows cross-sectional views of physiological systems in X-rays photography. Moreover, recent advancement is to make model and study physical functions to design artificial limbs and even plan and practice surgery. Computer-aided surgery is currently a hot topic.
VU
VU
VU
History and cultural heritage Another important application of computer graphics is in the field of history and cultural heritage. A lot of work is done in this area to preserve history and cultural heritage. The features so for provide are: Innovative graphics presentations developed for cultural heritage applications Interactive computer techniques for education in art history and archeology New analytical tools designed for art historians Computer simulations of different classes of artistic media 14 Copyright Virtual University of Pakistan
VU
VU
Movies Computer graphics methods are now commonly used in making motions pictures, music videos and television shows. Sometimes the graphics scenes are displayed by themselves and sometimes graphics objects are combined with the actors and live scenes. A number of hit movies and shows are made using computer graphics technology. Some of them are: Star Trek- The Wrath of Khan Deep Space Nine Stay Tuned Reds Dreams Shes Mad
Tron (1980) First time computer graphics were used for live action sequences.
VU
VU
VU
The Last Starfighter (15 minutes) (1982) The Last Starfighter (15 minutes) (1982)
VU
VU
Traditional Animated Features Some examples: Automating Keyframing in many Disney-type animations The flocking behaviour of the wild beast in Lion King Non photorealistic rendering: 3D effects in Futurama
VU
119,592 15 (approx.) 107 ft. 275,000 hrs. 6 MB 270 166 700 256 MB 54 yrs., 222 days, 15 mins., 36 3.2 TB 75000 frames 41.5 days (997 hrs.)
VU
Simulations Simulation by all means is a very helpful tool to show the idea you have or the work you are doing or to see the results of your work. Given below is the picture in which you can see waves ripples on water; no doubt looking like original but is simply a simulation. A number of software packages are used for simulation including: Crackerjack Computer Skills Keen Artistic Eye Flash Maya
Game Thanks to computer graphics, real time games are now possible. Now game programming itself has become an independent field and game programmers are in high demand. Some of the famous games are: Quake Dooms Need For Speed Commandos 23 Copyright Virtual University of Pakistan
VU
Related Disciplines
Data Processing Computer Vision DATA Computer Graphics IMAGES Image Processing
Interdisciplinary Science Physics: light, color, appearance, behavior Mathematics: Curves and Surfaces, Geometry and Perspective Engineering Hardware: graphics media and processors, input and output devices Software: graphics libraries, window systems Art, Perception and Esthetics Color, Composition, Lighting, Realism
2-Graphics Systems I
VU
Lecture No.2
Graphics Systems I
Introduction of Graphics Systems With the massive development in the field of computer graphics a broad range of graphics hardware and software systems is available. Graphics capabilities for both twodimensional and three-dimensional applications are now common on general-purpose computers, including many hand-held calculators. On personal computers there is usage of a variety of interactive input devices and graphics software packages; whereas, for higher-quality applications some special-purpose graphics hardware systems and technologies are employed. VIDEO DISPLAY DEVICES The primary output device in a graphics system is a video monitor. The operation of most video monitors is based on the standard cathode-ray-tube (CRT) design, but several other technologies exist and solid-state monitors may eventually predominate. Refresh Cathode-Ray Tubes Following figures illustrate the basic operation of a CRT. A beam of electrons (cathode rays) emitted by an electron gun, passes through focusing and deflection systems that direct the beam toward specified positions on the phosphor-coated screen. The phosphor then emits a small spot of light at each position contacted by the electron beam. The light emitted by the phosphor fades very rapidly therefore to keep the picture it is necessary to keep the phosphor glowing. This is achieved through redrawing the picture repeatedly by quickly directing the electron beam back over the same points and the display using this technique is called refresh CRT. The primary components of an electron gun in a CRT are the heated metal cathode and a control grid. Heat is supplied to the cathode by directing a current through filament (a coil of wire), inside the cylindrical cathode structure. Heating causes electrons to be boiled off the hot cathode surface. In the vacuum inside the CRT envelope, the free, negatively charged electrons are then accelerated toward the phosphor coating by a high positive voltage.
2-Graphics Systems I
VU
The accelerating voltage can be generated with a positively charged metal coating on the inside of the CRT envelope near the phosphor screen an accelerating anode can be used.
Intensity of the electron beam is controlled by setting voltage levels on the control grid, a metal cylinder that fits over the cathode. A high negative voltage applied to the control grid will shut off the beam by repelling electrons and stopping them from passing through the small hole at the end of the control grid structure. A smaller negative voltage on the control grid simply decreases the number of electrons striking the phosphor coating on the screen. It is the responsibility of focusing system to converge electron beam to a small spot where it strikes the phosphor. Otherwise the electrons will repel each other and the beam would disperse. This focusing is achieved through electric or magnetic fields. In electrostatic focusing the electron beam passes through a positively charged metal cylinder that forms an electrostatic lens. Then electrostatic lens focuses the electron beam at the center of the screen. Similar task can be achieved with a magnetic field setup by a coil mounted around the outside of the CRT envelope. Magnetic lens focusing produces the smallest spot size on the screen and is used in special purpose devices. The distance that the electron beam must travel from gun to the exact location of the screen that is small spot is different from the distance to the center of the screen in most CRTs because of the curvature therefore some additional focusing hardware is required in high precision systems to take beam to all positions of the screen. This procedure is achieved in two steps in first step beam is conveyed through the exact center of the screen 26 Copyright Virtual University of Pakistan
2-Graphics Systems I
VU
and then additional focusing system adjust the focusing according to the screen position of the beam. Cathode-ray tubes are now commonly constructed with magnetic deflection coils mounted on the outside of the CRT envelope. Two pairs of coils are used, with the coils in each pair mounted on opposite sides of the neck of the CRT envelope. One pair is mounted on the top and bottom of the neck and the other pair is mounted on opposite sides of the neck. The magnetic field produced by each pair of coils results in a traverse deflection force that is perpendicular both to the direction of the magnetic field and to the direction of travel of the electron beam. Horizontal deflection is achieved with one pair of coils, and vertical deflection by the other pair. The proper deflection amounts are attained by adjusting the current through the coils. When electrostatic deflection is used, two pairs of parallel plates are mounted inside the CRT envelope. One pair of plates is mounted horizontally to control the vertical deflection, and the other pair is mounted vertical to control horizontal deflection.
Phosphor is available in different kinds. One variety is available in color but a major issue is their persistence. Persistence is defined as the time it takes the emitted light from the phosphor to decay to one-tenth of its original intensity. Lower persistence phosphors require higher refresh rates to maintain a picture on the screen without flicker. A phosphor with low persistence is useful for displaying highly complex, static pictures. Monitors normally come with persistence in the range from 10 to 60 microseconds. The maximum number of points (that can be uniquely identified) on a CRT is referred to as the resolution. A more precise definition of resolution is the number of points per centimeter that can be plotted horizontally and vertically, although it is often simply stated as the total number of points in each direction. Finally aspect ratio; is the ratio of vertical points to horizontal points necessary to produce equal-length lines in both directions on the screen. An aspect ratio of 3/4 means that a vertical line plotted with three points has the same length as a horizontal line plotted with four points. RASTER-SCAN SYSTEMS Raster scan is the most common type of monitors using CRT. In raster scan picture is stored in the area called refresh buffer or frame buffer. First of all why information is stored; because picture have to be refreshed again and again for this very reason it is stored. Second is how it is stored; so picture is stored in a two dimensional matrix where each element corresponds to each pixel on the screen. If there arise a question what is a pixel? The very simple answer is a pixel (short for picture element) represents the shortest 27 Copyright Virtual University of Pakistan
2-Graphics Systems I
VU
possible unique position/ element that can be displayed on the monitor without overlapping. The frame buffer stores information in a two dimensional matrix; the question is that how many bits are required for each pixel or element. If there is black and white picture then there is only one bit required to store 0 for black or 1 for white and in this case buffer will be referred as bitmap. In colour pictures obviously multiple bits are required for each pixel position depending on the possible number of colours for example to show 256 colours 8 bits will be required for each pixel and in case if multiple bits are used for one pixel frame buffer will be referred as pixmap. Now with the information in frame buffer, let us see how an image is drawn. The drawing is done in a line-by-line fashion. After drawing each line from left to right it reaches at the left end of the next line to draw next line; which is called horizontal retrace. Similarly after completing all lines in horizontal fashion it again reaches the top left corner to start redrawing the image (that is for refreshing) and this is called vertical retrace. Normally each vertical retrace takes 1/60th of a second to avoid flickering. There are two further methods to scan the image: interlaced and non-interlaced. In interlaced display beam completes scanning in two passes. In one pass only odd lines are drawn and in the second pass even lines are drawn. Interlacing provides effect of double refresh rate by completing half of the lines in half of the time. Therefore, in systems with low refresh rates interlacing helps avoid flickering.
RANDOM-SCAN Displays In random-scan displays a portion of the screen can be displayed. Random-scan displays draw a picture one line at a time and are also called vector displays (or stroke-writing or calligraphic displays). In these systems image consists of a set of line drawing commands referred to as Refresh Display File. Random-scan can refresh the screen in any fashion by repeating line drawing mechanism. Random-scan displays are designed to draw all the component lines of a picture 30 to 60 times each second. High-quality vector systems are capable of handling approximately 100,000 short lines at this refresh rate. When a small set of lines is to be displayed, each refresh cycle is delayed to avoid refresh rates greater than 60 frames per second. Otherwise, faster refreshing of the set of lines could burn out the phosphor. Random-scan displays are designed for line-drawing applications and cannot display complex pictures. The lines drawn in vector displays are smoother whereas in raster-scan lines often become jagged. Color CRT Monitors A CRT monitor displays colour pictures by using a combination of phosphors that emit different coloured light. With the combination of phosphor a range of colours can be displayed. There are two techniques used in colour CRT monitors: Beam Penetration Method Shadow Mask Method 28 Copyright Virtual University of Pakistan
2-Graphics Systems I
VU
In beam penetration method two layers of phosphor, usually coated onto the inside of the CRT screen, and the displayed colour depend on how far the electron beam penetrates into the phosphor layers. At intermediate beam speeds, combinations of red and green light are emitted to show two additional colours, orange and yellow. Beam penetration is an inexpensive way to produce colours as only a few colours are possible and the quality of picture is also not impressive. Shadow mask methods can display a wide range of colours. In this technique each pixel position is made up of three phosphor dots called triads as shown in the following figure. Three phosphor dots have different colors i.e. red, green and blue and the display colour is made by the combination of all three dots. Three guns are used to throw beam at the three dots of the same pixel. By varying intensity at each dot a wide range of colours can be generated. A shadow-mask is used which has holes aligned with the dots so that each gun can fire beam to corresponding dot only. CRT Displays Advantages Fast response (high resolution possible) Full colour (large modulation depth of E-beam) Saturated and natural colours Inexpensive, matured technology Wide angle, high contrast and brightness Disadvantages Large and heavy (typ. 70x70 cm, 15 kg) High power consumption (typ. 140W) Harmful DC and AC electric and magnetic fields Flickering at 50-80 Hz (no memory effect) Geometrical errors at edges Direct View Storage Devices A direct view storage tube stores the picture information as a charge distribution just behind the phosphor-coated screen. Two electron guns are used in this system as shown in the following figure. They are: Primary Gun Flood Gun
Primary gun is used to store the picture pattern whereas flood gun maintains the picture display. 29 Copyright Virtual University of Pakistan
2-Graphics Systems I
VU
DVST has advantage that no refresh is required so very complex pictures can be displayed at very high resolutions without flicker. Whereas, it has disadvantage that ordinarily no colors can be displayed and that selected parts of a picture cannot be erased. To eliminate a picture section, the entire screen must be erased and the modified picture redrawn. The erasing and redrawing process can take several seconds for a complex picture. Flat-Panel Displays This is emerging technology slowly replacing CRT monitors. The flat-panel displays have following properties: Little Volume Light Weight Lesser Power consumption
Flat panels are used in calculators, pocket video games and laptop computers. There are two categories of flat panel displays: Emissive Display (Plasma Panels) Non-Emissive Display (Liquid Crystal Display) The emissive displays (emitters) are devices that convert electrical energy into light. Plasma panels, thin-film electro-luminescent displays, and light-emitting diodes are examples of emissive displays. Non-emissive displays (non-emitters) use optical effects to convert sunlight or light from some other source into graphics patterns. The most important example of a non-emissive flat-panel display is a liquid-crystal device. Plasma-panel Displays Plasma panels also called gas-discharge displays are constructed by filling the region between two glass plates with a mixture of gases that usually includes neon. A series of vertical conducting ribbons is placed on one glass panel, and a set of horizontal ribbons is built into the other glass panel. Firing voltages applied to a pair of horizontal and vertical conductors cause the gas at the intersection of the two conductors to break down into glowing plasma of electrons and ions. Picture definition is stored in a refresh buffer, and the firing voltages are applied to refresh the pixel positions 60 times per second. Advantages Large viewing angle 30 Copyright Virtual University of Pakistan
2-Graphics Systems I
VU
Good for large-format displays Fairly bright Disadvantages Expensive Large pixels (~1 mm versus ~0.2 mm) Phosphors gradually deplete Less bright as compared to CRTs, using more power Liquid Crystal Displays Liquid crystal refers to the fact that these compounds have a crystalline arrangement of molecules, yet they flow like a liquid. Flat panel displays use nematic liquid crystal, as demonstrated in the following figures. Two glass plates, each containing a light polarizer at right angles to the other plate, sandwich the liquid-crystal material. Rows of horizontal transparent conductors are built into one glass plate, and columns of vertical conductors are put into the other plate. The intersection of two conductors defines a pixel position. Polarized light passing through the material is twisted so that it will pass through the opposite polarizer. The light is then reflected back to the viewer. To turn off the pixel, we apply a voltage to the two intersecting conductors to align the molecules so that the light is not twisted. LCD Displays Advantages Small footprint (approx 1/6 of CRT) Light weight (typ. 1/5 of CRT) Low power consumption (typ. 1/4 of CRT) Completely flat screen - no geometrical errors Crisp pictures - digital and uniform colours No electromagnetic emission Fully digital signal processing possible Large screens (>20 inch) on desktops Disadvantages High price (presently 3x CRT) Poor viewing angle (typ. +/- 50 degrees) Low contrast and luminance (typ. 1:100) Low luminance (Natural light) (typ. 200 cd/m2) 31 Copyright Virtual University of Pakistan
2-Graphics Systems I
VU
Three-Dimensional Viewing Devices Graphics monitors for the display of three-dimensional scenes have been devised using a technique that reflects a CRT image from a vibrating, flexible mirror. In this system when varifocal mirror vibrates it changes focal length. These vibrations are synchronized with the display of an object on a CRT so that each point on the object is reflected from the mirror into spatial position corresponding to the distance of that point from a specified viewing position. This allows user to walk around an object or scene and view it from different sides. Virtual Reality Devices Virtual reality system enables users to move and react in a computer-simulated environment. Various types of devices allow users to sense and manipulate virtual objects much as they would real objects. This natural style of interaction gives participants the feeling of being immersed in the simulated world. Virtual reality simulations differ from other computer simulations in that they require special interface devices that transmit the sights, sounds, and sensations of the simulated world to the user. These devices also record and send the speech and movements of the participants to the simulation program. To see in the virtual world, the user wears a head-mounted display (HMD) with screens directed at each eye. The HMD contains a position tracker to monitor the location of the user's head and the direction in which the user is looking. Using this information, a computer recalculates images of the virtual world to match the direction in which the user is looking and displays these images on the HMD. Users hear sounds in the virtual world through earphones in the HMD. The hepatic interface, which relays the sense of touch and other physical sensations in the virtual world, is the least developed feature. Currently, with the use of a glove and position tracker, the user can reach into the virtual world and handle objects but cannot actually feel them. 32 Copyright Virtual University of Pakistan
2-Graphics Systems I
VU
Another interesting simulation is interactive walk through. A sensing system in the headset keeps track of the viewers opposition, so that the front and back of objects can be seen as the viewer walks and interacts with the displays. Similarly given below is a figure using a headset and a data glove worn on the right hand?
3-Graphics Systems II
VU
Lecture No.3
Raster-Scan Systems
Graphics Systems II
Interactive raster graphics systems typically employ several processing units. In addition to the CPU, a special purpose processor, called the video controller or display controller is used to control the operation of the display device. Organization of a simple raster system is shown in following figure. Here the frame buffer can be anywhere in the system memory, and the video controller accesses the frame buffer to refresh the screen.
Architecture of a simple raster graphics system In addition to the video controller more sophisticated raster systems employ other processors as coprocessors and accelerators to implement various graphics operations. Video Controller Following figure shows a commonly used organization for raster systems. A fixed area of the system memory is reserved for the frame buffer, and the video controller is given direct access to the frame-buffer memory. Frame-buffer locations, and the corresponding screen positions, are referenced in Cartesian coordinates.
3-Graphics Systems II
VU
Architecture of a raster system with a fixed portion of a system memory reserved for the frame buffer. In the following figure the basic refresh operations of the video controller are diagrammed. Two registers are used to store the coordinates of the screen pixels. Initially, the x register is set to 0 and the y register is set to ymax. The value stored in the frame buffer for this pixel position is then retrieved and used to set the intensity of the CRT beam. Then the x register is incremented by 1, and the process repeated for the next pixel on the top scan line. This procedure is repeated for each pixel along the next line by resetting x register to 0 and decrementing the y register by 1. Pixels along this scan line are then processed in turn, and the procedure is repeated for each successive scan line. After cycling through all pixels along the bottom scan line y=0, the video controller resets to the first pixel position on the top scan line and the refresh process starts over.
Raster Scan Generator
Register X
Register Y
Memory Addresses
Pixel Register
Intensity
Frame Buffer
Basic Video Controller Refresh Operations Since the screen must be refreshed at the rate of 60 frames per second, the simple procedure illustrated in above figure cannot be accommodated by typical RAM chips. The cycle time is too large making the process very slow. To speed up pixel processing, video controllers can retrieve multiple pixel values from the refresh buffer on each pass. 35 Copyright Virtual University of Pakistan
3-Graphics Systems II
VU
The multiple pixel intensities are then stored in a separate register and used to control the CRT beam intensity for a group of adjacent pixels. When that group of pixels has been processed, the next block of pixel values is retrieved from the frame buffer. Raster Scan Display Processor Following figure shows one way to setup the organization of a raster system containing a separate display processor, sometimes referred to as a graphics controller or a display coprocessor. The purpose of the display processor is to free the CPU from the graphics chores. In addition to the system memory, a separate display processor memory area can also be provided. A major task of the display processor is digitizing a picture definition given in an application program into a set of pixel-intensity values for storage in the frame buffer. This digitization process is called scan conversion.
Display Processor Memory Frame Buffer Video Controller Monitor
CPU
Display Processor
System Memory
System Bus
I/O Devices
Architecture of a raster graphics system with a display processor Raster-Scan Characters Graphics commands specifying straight lines and other geometric objects are scan converted into a set of discrete intensity points. Scan converting a straight-line segment, for example, means that we have to locate the pixel positions closest to the line path and store the intensity for each position in the frame buffer. Similar methods are used for scan converting curved lines and polygon outlines. Characters can be defined with rectangular grids, as shown in following figure, or they can be defined with curved outlines shown in the right hand side figure given below. The array size for character grids can vary from about 5 by 7 to 9 by 12 or more for higherquality displays. A character grid is displayed by superimposing the rectangular grid pattern into the frame buffer at a specified coordinate position. With characters that are defined as curve outlines, character shapes are scan converted into the frame buffer.
3-Graphics Systems II
VU
Random-Scan Systems The organization of a simple random scan system is shown in following figure. An application program is input and stored in the system memory along with a graphics package. Graphics commands in the application program are translated by the graphics package into a display file stored in the system memory. This display file is then accessed by the display processor to refresh the screen. The display processor cycles through each command in the display file program once during every refresh cycle. Sometimes the display processor in a random scan system is referred to as a display processing unit or graphics controller.
Architecture of a simple random scan system Graphics Card or Display Adapters A video card is typically an adapter, a removable expansion card in the PC. Thus, it can be replaced! A video display adapter which is the special printed circuit board that plugs into one of the several expansion slots present on the mother board of the computer. A video display adapter is simply referred as a video card. The video card can also be an integral part of the system board; this is the case in certain brands of PCs and is always the case in laptops and clear preference for the replaceable video card in some PCs. 37 Copyright Virtual University of Pakistan
3-Graphics Systems II
VU
A number of display adapters are available with varying capabilities especially Intel systems support following adapters: Monochrome Adapter (MA) Hercules Adapter (HA) Color Graphics Adapter (CGA) Enhanced Graphics Adapter (EGA) Multicolor Graphics Adapter (MCGA) Video Graphics Adapter (VGA) Super Video Graphics Adapter (SVGA) Extended Graphics Adapter (XGA)
Monochrome Adapter The simplest and the first available adapter is MA. This adapter can display only text in single color and has no graphics displaying capability. Originally this drawback only prevented the users from playing video games, but today, even the most serious business software uses graphics and color to great advantage. Hence, MA is no longer suitable, though it offers clarity and high resolution. Hercules Adapter The Hercules card emulates the monochrome adapter but also operates in a graphics mode. Having graphics capabilities the Hercules card became somewhat of a standard for monochrome systems. Color Graphics Adapter This adapter can display text as well as graphics. In text mode it operates in 25 rows by 80 column mode with 16 colors. In graphics mode two resolutions are available: Medium resolution graphics mode 320 * 200 with 4 colors available from palette of 16 colors and 640 * 200 with 2 colors
One drawback of CGA card is that it produces flicker and snow. Flicker is the annoying tendency of the text to flash as it moves up or down. Snow is the flurry of bright dots that can appear anywhere on the screen. Enhanced Graphics Adapter The EGA was introduced by IBM in 1984 as alternative to CGA card. The EGA could emulate most of the functions and all the display modes of CGA and MA. The EGA offered high resolution and was not plagued with the snow and flicker problems of CGA. In addition EGA is designed to use the enhanced color monitor capable of displaying 640 * 350 in 16 colors from a palette of 64. The EGA card has several internal registers. A serious limitation of the EGA card is that it supports write operations to most of its internal registers, but no read operation. The result is it is not possible for software to detect and preserve the state of the adapter, which makes EGA unsuited for memory resident application or for multitasking like windows and OS/2.
3-Graphics Systems II
VU
Multicolor Graphics Adapter The MCGA was designed to emulate the CGA card and to maintain compatibility with all the CGA modes. In addition to the text and graphics modes of the CGA, MCGA has two new graphics modes: 640 * 480 with 2 colors 320 * 200 in with 256 colors Video Graphics Adapter The VGA supports all the display modes of MA, CGA and MCGA. In addition VGA supports a graphics mode of 640 * 480 with 16 colors. Super Video Graphics Adapter The SVGA designation refers to enhancements to the VGA standard by independent vendors. Unlike display adapters discussed earlier SVGA does not refer to a card that meets a particular specification but to a group of cards that have different capabilities. For example one card may have resolutions 800 * 600 and 1024 * 768, whereas, another card may have same resolution but more colors. These cards have different capabilities, but still both of them are classified as SVGA. Since each SVGA card has different capabilities, you need special device driver programs for driving them. This means that unlike VGA cards which can have a single driver that works with all VGA cards, regardless of the vendor, each SVGA card must have a corresponding driver. Extended Graphics Adapter The XGA evolved from the VGA and provides greater resolution, more colors and much better performance. The XGA has a graphics processor bus mastering. Being a bus master adapter means that the XGA can take control of the system as though it were the mother board. In essence, a bus master is an adapter of the mother board. The XGA offers 2 new modes: 640 * 480 with 16 bit colors (65536 colors) 1024 * 768 with 8 bit colors (256 colors) Video Card Supports the CPU The video card provides a support function for the CPU. It is a processor like the CPU. However it is especially designed to control screen images.
3-Graphics Systems II
VU
RAM on the Video Card Video cards always have a certain amount of RAM. This RAM is also called the frame buffer. Today video cards hold plenty of RAM, but earlier it was more important: How much RAM? That is significant for color depth at the highest resolutions. Which type of RAM? This is significant for card speed. Video card RAM is necessary to keep the entire screen image in memory. The CPU sends its data to the video card. The video processor forms a picture of the screen image and stores it in the frame buffer. This picture is a large bit map. It is used to continually update the screen image. 3D - lots of RAM Supporting the demand for high quality 3D performance many new cards come with a frame buffer of 16 or 32 MB RAM and they use the AGP interface for better bandwidth and access to the main memory. VRAM Briefly, in principle all common RAM types can be used on the video card. Most cards use very fast editions of ordinary RAM (SDRAM or DDR). Some high end cards (like Matrox Millennium II) earlier used special VRAM (Video RAM) chips. This was a RAM type, which only was used on video cards. In principle, a VRAM cell is made up of two ordinary RAM cells, which are "glued" together. Therefore, you use twice as much RAM than otherwise. VRAM also costs twice as much. The smart feature is that the double cell allows the video processor to simultaneously read old and write new data on the same RAM address. Thus, VRAM has two gates which can be active at the same time. Therefore, it works significantly faster. With VRAM you will not gain speed improvements increasing the amount of RAM on the graphics controller. VRAM is already capable of reading and writing simultaneously due to the dual port design. UMA and DVMT On some older motherboards the video controller was integrated. Using SMBA (Shared Memory Buffer Architecture) or UMA (Unified Memory Architecture) in which parts of the system RAM were allocated and used as frame buffer. But sharing the memory was very slow and the standards never became very popular. A newer version of this is found in Intel chip set 810 and the better 815, which also integrates the graphics controller and use parts of the system RAM as frame buffer. Here the system is called Dynamic Video Memory Technology (D.V.M.T.). The RAMDAC All traditional graphics cards have a RAMDAC chip converting the signals from digital to analog form. CRT monitors work on analog signals. The PC works with digital data which are sent to the graphics adapter. Before these signals are sent to the monitor they have to be converted into analog output and this is processed in the RAMDAC: 40 Copyright Virtual University of Pakistan
3-Graphics Systems II
VU
The recommendation on a good RAMDAC goes like this: External chip, not integrated in the VGA chip Clock speed: 250 - 360 MHz. Heavy Data Transport The original VGA cards were said to be "flat." They were unintelligent. They received signals and data from the CPU and forwarded them to the screen, nothing else. The CPU had to make all necessary calculations to create the screen image. As each screen image was a large bit map, the CPU had to move a lot of data from RAM to the video card for each new screen image. The graphic interfaces, like Windows, gained popularity in the early nineties. That marked the end of the "flat" VGA cards. The PC became incredibly slow, when the CPU had to use all its energy to produce screen images. You can try to calculate the required amount of data. A screen image in 1024 x 768 in 16 bit color is a 1.5 MB bit map. That is calculated as 1024 x 768 x 2 bytes. Each image change (with a refresh rate of 75 HZ there is 75 of them each second) requires the movement of 1.5 MB data. That zaps the PC energy, especially when we talk about games with continual image changes. Furthermore, screen data have to be moved across the I/O bus. In the early nineties, we did not have the PCI and AGP buses, which could move large volumes of data. The transfer took place through the ISA bus, which has a very limited width. Additionally the CPUs were 386s and early 486s, which also had limited power. Accelerator Cards In the early nineties the accelerator video cards appeared. Today all cards are accelerated and they are connected to the CPU through high speed buses like PCI and AGP. With accelerated video chips, Windows (and with that the CPU) need not calculate and design the entire bit map from image to image. The video card is programmed to draw lines, Windows and other image elements. The CPU can, in a brief code, transmit which image elements have changed since the last transmission. This saves the CPU a lot of work in creating screen images. The video chip set carries the heavy load: All video cards are connected to the PCI or the AGP bus, this way providing maximum data transmission. The AGP bus is an expanded and improved version of the PCI bus used for video cards only. 41 Copyright Virtual University of Pakistan
3-Graphics Systems II
VU
Modern video cards made for 3D gaming use expensive high-end RAM to secure a sufficient bandwidth. If you for example want to see a game in a resolution of 1280 x 1024 at 80 Hz, you may need to move 400 MB of data each second - that is quite a lot. The calculation goes like this: 1280 X 1024 pixels x 32 bit (color depth) x 80 = 419,430,400 bytes 419,430,400 bytes = 409,600 kilobytes = 400 megabytes.
Graphics Libraries Graphics developers some time use 2D or 3D libraries to create graphics rapidly and efficiently. These developers include game developers, animators, designers etc. The following libraries are commonly used among developers: FastGL OpenGL DirectX Others Advantages of Graphics Libraries These libraries help developers to create fast and optimized animations and also help to access features that are available in video hardware. Hardware manufacturers give support in hardware for libraries. Famous manufacturers include SIS, NVIDIA, ATI, INTEL etc. Graphics Software There is a lot of 2D and 3D software available in the market. These software provide visual interface for creation of 2D and 3D animation / models image creation. These tools are under use of movie makers, professional animators and designers. These tools are flash, Maya, 3D studio max, adobe photo shop, CorelDraw, image viewer, paintbrush etc.
4-Point
VU
Lecture No.4
Point
Pixel: The smallest dot illuminated that can be seen on screen. Picture: Composition of pixels makes picture that forms on whole screen Resolution We know that Graphics images on the screen are built up from tiny dots called picture elements or pixels. The display resolution is defined by the number of rows from top to bottom, and number of pixels from left to right on each scan line. Since each mode uses a particular resolution. For example mode 19 uses a resolution of 200 scan lines, each containing 320 pixels across. This is often referred to as 320*200 resolution. In general, higher the resolution, more pleasing is the picture. Higher resolution means a sharper, clearer picture, with less pronounced staircase effect on lines drawn diagonally and better looking text characters. On the other hand, higher resolution also means more memory requirement for the display. Text and Graphics Modes We discussed different video hardware devices that include VGA cards and monitors. Video cards are responsible to send picture data to monitor each time it refresh itself. Video cards support both different text and graphics modes. Modes consist of their own refresh rate, number of colors and resolutions (number of rows multiply by number of columns). The following famous video modes that we can set in todays VGA cards on different refresh rate: 25 * 80 with 16 colors support (text mode) 320 * 200 with 8 bit colors support (graphics mode) 640 * 480 with 16 colors support (graphics mode) 640 * 480 with 8, 16, 24, 32 bit color support (graphics mode) 800 * 600 with 8, 16, 24, 32 bit color support (graphics mode) Text and Graphics All modes are fundamentally of two types, text or graphics. Some modes display only text and some are made only for graphics. As seen earlier, the display adapter continuously dumps the contents of the VDU (video display unit) memory on the screen. The amount of memory required representing a character on screen in text mode and a pixel in graphics mode varies from mode to mode. Mode No. 3 6 7 18 19 Type Text Graphics Text Graphics Graphics Resolution 80 x 25 640 x 200 80 x 25 640 x 480 320 x 200 Memory Required 2 bytes per char 1 bit per pixel 2 bytes per char 1 bit per pixel 1 byte per pixel 43 Copyright Virtual University of Pakistan
4-Point
VU
In mode 6 each pixel displayed on the screen occupies one bit in VDU memory. Since this bit can take only two values, either 0 or 1, only two colors can be used with each pixel. How text displays As seen previously text modes need two bytes in VDU memory to represent one character on screen; of these two bytes, the first byte contains the ASCII value of the character being displayed, whereas the second byte is the attribute byte. The attribute byte controls the color in which the character is being displayed. The ASCII value present in VDU memory must be translated into a character and drawn on the screen. This drawing is done by a character generator this is part of the display adapter or in VBIOS. The CGA has a character generator that uses 8 scan lines and 8 pixels in each of these scan lines to produce a character on screen; whereas the MAs character generator uses 9 scan lines and 14 pixels in each of these scan lines to produce a character. This larger format of MA makes the characters generated by MA much sharper and hence easier to read. On older display adapters like MA and CGA, the character generator is located in ROM (Read Only Memory). EGA and VGA do not have a character generator ROM. Instead, character generator data is loaded into plane 2 of display RAM. This feature makes it easy for custom character set to be loaded. Multiple character sets (up to 4 for EGA and up to 8 for VGA) may reside in RAM simultaneously. A set of BIOS services is available for easy loading of character sets. Each character set can contain 256 characters. Either one or two character sets may be active giving these adapters on the screen simultaneously. When two character sets are active, a bit in each character attribute byte selects which character set will be used for that character. Using a ROM-BIOS service we can select the active character set. Each character in the standard character set provided with the EGA is 8 pixels wide and 14 pixels tall. Since VGA has higher resolution, it provides a 9 pixel wide by 16 pixels tall character set. Custom character set can also be loaded using BIOS VDU services. The graphics modes can also display characters, but they are produced quite differently. The graphics modes can only store information bit by bit. The big advantage of this method is that you design characters of desired style, shape and size. Text mode colors In mode 3, for each character on screen there are two bytes in VDU memory, one containing the ACCII value of the character and other containing its attribute. The attribute byte controls the color of the character. The attribute byte contains three components: the foreground color (color of the character itself), the background color (color of the area not covered by the character) and the blinking component of the character. The next slide shows the breakup of the attribute byte.
4-Point
VU
7 X X X X X X X 1
Bits 6 x x x x x x 1 x
5 x x x x x 1 x x
x x x x 1 x x x
4 x x x 1 x x x x
3 x x 1 x x x x x
2 x 1 x x x x x x
1 1 x x x x x x x
Purpose Blue component of foreground color Green component of foreground color Red component of foreground color Intensity component of foreground color Blue component of background color Green component of background color Red component of background color Blinking component
Graphics Mode colors So far we have seen how to set color in text modes. Setting color in graphics modes is quite different. In the graphics mode each pixel on the screen has a color associated with it. There are important differences here as compared to setting color in text mode. First, the pixels cannot blink. Second, each pixel is a discrete dot of color, there is no foreground and background. Each pixel is simply one color or another. The number of colors that each adapter can support and the way each adapter generates these colors is drastically different. But we will only discuss here colors in VGA. Colors in VGA IBM first introduced the VGA card in April 1987. VGA has 4 color planes red, green, blue and intensity, with one bit from each of these planes contributing towards 1 pixel value. There are lots of ways that you can write pixel on screen. You can write pixel on screen by using one of the following methods: Using video bios services to write pixel Accessing memory and registers directly to write pixel on screen. Using library functions to write pixel on screen Practical approach to write pixel on screen As we have discussed three ways to write pixel on screen. Here we will discuss all these ways practically and see how the pixel is displayed on screen. For that we will have to write code in Assembly and C languages. So get ready with these languages Writing pixel Using Video BIOS The following steps are involved to write pixel using video BIOS services. Setting desired video mode Using bios service to set color of a screen pixel Calling bios interrupt to execute the process of writing pixel.
Source code Below are the three lines written in assembly language that can set graphics mode 19(13h). You can use this for assembler or you can embed this code in C language using asm keyword 45 Copyright Virtual University of Pakistan
4-Point
VU
MOV AH,0 MOV AL,13h ;;mode number from 0-19 INT 10H To insert in C language above code will be inserted with key word asm and curly braces. asm{ MOV AH,0 MOV AL,13h ;;mode number from 0-19 INT 10H } Description Line #1: mov ah,0 is the service number for setting video mode that is in register ah Line #2: mov al,13h is the mode number that is in register al Line #3: int 10h is the video bios interrupt number that will set mode 13h Source code for writing pixel The following code can be used to write pixel using video bios interrupt 10h and service number 0ch. MOV AH,0Ch MOV AL,COLOR_NUM MOV BH,0 MOV CX,ROW_NUM MOV DX,COLUMN_NUM INT 10h Description Line#1: service number in register Ah Line#2: color value, since it is 13h mode so it has 0-255 colors range. You can assign any color number from 0 to 255 to all register. Color will be selected from default palette setting against the number you have used. Line#3: page number in Bh register. This mode supports only one page. So 0 is used in Bh register. 0 mean default page. Line#4: column number will be used in CX register Line#5: row number will be used in DX register Line#6: BIOS interrupt number 10h
Writing pixel by accessing memory directly So far we used BIOS to draw pixel. Here we will draw pixel by accessing direct pointer to the video memory and write color value. The following steps are involved to write direct pixel without using BIOS: Set video mode by using video BIOS routine as discussed earlier Set any pointer to the video graphics memory address 0x0A0000. Now write any color value in the video memory addressing
4-Point
VU
Direct Graphics Memory Access Code Mov ax,0a000h Mov ds,ax ;;segment address changed Mov si,10 ;; column number Mov [si],COLOR_NUM Work to do: Write pixel at 12th row and 15th column Hint: use formula (row * 320 + column) in si register. Writing character directly on screen You can also write direct text by setting any text mode using BIOS service and then setting direct pointer at text memory address 0x0b8000. Example Set mode Number 3. using BIOS service and then use this code to write character Mov ax,0b8000h Mov ds,ax Mov si,10 Mov [si],a
Using Library functions While working in C language, you can use graphics library functions to write pixel on screen. These graphics library functions then use BIOS routines or use direct memory access drivers to draw pixel on screen. initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", getch()); /* return with error code */ } /* draw a pixel on 10th row and 10 column */ putpixel(10, 10, BLUE); /* clean up */ closegraph();
exit(1);
Steps in C language First call Initgraph() function and then call putpixel() function to draw pixel on screen. It takes row, column and color value as parameters. after drawing pixel use closegraph() function to close the graphics routines provided by built in driver by Borland.
4-Point
VU
Discussion on pixel drawing methods BIOS routines are standard routines built in VGA cards but these routines are very much slow. You will use pixel to draw filled triangle, rectangles and circles and these all will be much slower than direct memory access method. Direct memory access method allows you to write pixel directly by passing the complex BIOS routines. It is easy and faster but its programming is only convenient in mode 13h. Library functions are easier to use and even faster because these are optimized and provided with special drivers by different companies. Drawing pixel in Microsoft Windows So far we have been discussing writing pixel in DOS. Here we will discuss briefly how to write pixel in Microsoft Windows. Microsoft windows are a complete graphical operating system but it does not allow you to access BIOS or direct memory easily. It provides library functions (APIs) that can be used to write graphics. By working in graphics in windows one must have knowledge about Windows GDI (graphics device interface) system. Windows GDI functions Here are some windows GDI functions that can be used to draw pixel e.g SetPixel and SetPixelV. Both are used to draw pixel on screen. The example and source code of writing pixel in windows will be available. Window Code Example: // a.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "resource.h" #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text
//
current
// Foward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 48 Copyright Virtual University of Pakistan
4-Point
VU
{ // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_A, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_A); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; } // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage is only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; 49 Copyright Virtual University of Pakistan
4-Point
VU
wcex.lpfnWndProc wcex.cbClsExtra wcex.cbWndExtra wcex.hInstance wcex.hIcon wcex.hCursor wcex.hbrBackground wcex.lpszMenuName wcex.lpszClassName wcex.hIconSm
= (WNDPROC)WndProc; = 0; = 0; = hInstance; = LoadIcon(hInstance, (LPCTSTR)IDI_A); = LoadCursor(NULL, IDC_ARROW); = (HBRUSH)(COLOR_WINDOW+1); = (LPCSTR)IDC_A; = szWindowClass; = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);
return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HANDLE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu 50 Copyright Virtual University of Pakistan
4-Point
VU
// WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; TCHAR szHello[MAX_LOADSTRING]; LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING); switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... RECT rt; GetClientRect(hWnd, &rt); int j=0; //To draw some pixels of RED colour on the screen for(int i=0;i<100;i++) { SetPixel(hdc,i+j,10,RGB(255,0,0)); j+=6; } EndPaint(hWnd, &ps); } break; 51 Copyright Virtual University of Pakistan
4-Point
VU
case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Mesage handler for about box. LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; }
VU
Lecture No.5
Line A line, or straight line, is, roughly speaking, an (infinitely) thin, (infinitely) long, straight geometrical object, i.e. a curve that is long and straight. Given two points, in Euclidean geometry, one can always find exactly one line that passes through the two points; this line provides the shortest connection between the points and is called a straight line. Three or more points that lie on the same line are called collinear. Two different lines can intersect in at most one point; whereas two different planes can intersect in at most one line. This intuitive concept of a line can be formalized in various ways. A line may have three forms with respect to slope i.e. it may have slope = 1 as shown in following figure (a), or may have slope < 1 as shown in figure (b) or it may have slope > 1 as shown in figure (c). Now if a line has slope = 1 it is very easy to draw the line by simply starting form one point and go on incrementing the x and y coordinates till they reach the second point. So that is a simple case but if slope < 1 or is > 1 then there will be some problem.
figure (a)
figure (b)
figure (c)
There are three techniques to be discussed to draw a line involving different time complexities that will be discussed later. These techniques are: Incremental line algorithm DDA line algorithm Bresenham line algorithm
Incremental line algorithm This algorithm exploits simple line equation y = m x + b Where m = dy / dx and b=ymx Now check if |m| < 1 then starting at the first point, simply increment x by 1 (unit increment) till it reaches ending point; whereas calculate y point by the equation for each x and conversely if |m|>1 then increment y by 1 till it reaches ending point; whereas calculate x point corresponding to each y, by the equation. Now before moving ahead let us discuss why these two cases are tested. First if |m| is less than 1 then it means that for every subsequent pixel on the line there will be unit increment in x direction and there will be less than 1 increment in y direction and vice versa for slope greater than 1. Let us clarify this with the help of an example: 53 Copyright Virtual University of Pakistan
VU
Suppose a line has two points p1 (10, 10) and p2 (20, 18) Now difference between y coordinates that is dy = y2 y1 = 18 10 = 8 Whereas difference between x coordinates is dx = x2 x1 = 20 10 = 10 This means that there will be 10 pixels on the line in which for x-axis there will be distance of 1 between each pixel and for y-axis the distance will be 0.8. Consider the case of another line with points p1 (10, 10) and p2 (16, 20) Now difference between y coordinates that is dy = y2 y1 = 20 10 = 10 Whereas difference between x coordinates is dx = x2 x1 = 16 10 = 6 This means that there will be 10 pixels on the line in which for x-axis there will be distance of 0.6 between each pixel and for y-axis the distance will be 1. Now having discussed this concept at length let us learns the algorithm to draw a line using above technique, called incremental line algorithm: Incremental_Line (Point p1, Point p2) dx = p2.x p1.x dy = p2.y p1.y m = dy / dx x = p1.x y = p1.y b=ym*x if |m| < 1 for counter = p1.x to p2.x drawPixel (x, y) x=x+1 y=m*x+b else for counter = p1.y to p2.y drawPixel (x, y) y=y+1 x=(yb)/m Discussion on algorithm: Well above algorithm is quite simple and easy but firstly it involves lot of mathematical calculations that is for calculating coordinate using equation each time secondly it works only in incremental direction. We have another algorithm that works fine in all directions and involving less calculation mostly only addition; which will be discussed in next topic. Digital Differential Analyzer (DDA) Algorithm: DDA abbreviated for digital differential analyzer has very simple technique. Find difference dx and dy between x coordinates and y coordinates respectively ending points of a line. If |dx| is greater than |dy|, than |dx| will be step and otherwise |dy| will be step. if |dx|>|dy| then step = |dx| else 54 Copyright Virtual University of Pakistan
VU
step = |dy|
Now very simple to say that step is the total number of pixel required for a line. Next step is to divide dx and dy by step to get xIncrement and yIncrement that is the increment required in each step to find next pixel value. xIncrement = dx/step yIncrement = dy/step Next a loop is required that will run step times. In the loop drawPixel and add xIncrement in x1 by and yIncrement in y1. To sum-up all above in the algorithm, we will get, DDA_Line (Point p1, Point p2) dx = p2.x p1. x dy = p2.y p1. y x1=p1.x y1=p1.y if |dx|>|dy| then step = |dx| else step = |dy| xIncrement = dx/step yIncrement = dy/step for counter = 1 to step drawPixel (x1, y1) x1 = x1 + xIncrement y1 = y1 + yIncrement Criticism on Algorithm: There is serious criticism on the algorithm that is use of floating point calculation. They say that when we have to draw points that should have integers as coordinates then why to use floating point calculation, which requires more space as well as they have more computational cost. Therefore there is need to develop an algorithm which would be based on integer type calculations. Therefore, work is done and finally we will come up with an algorithm Bresenham Line Drawing algorithm which will be discussed next. Bresenham's Line Algorithm Bresenham's algorithm finds the closest integer coordinates to the 55 Copyright Virtual University of Pakistan
VU
actual line, using only integer math. Assuming that the slope is positive and less than 1, moving 1 step in the x direction, y either stays the same, or increases by 1. A decision function is required to resolve this choice. If the current point is (xi, yi), the next point can be either (xi+1,yi) or (xi+1,yi+1) . The actual position on the line is (xi+1, m(xi+1)+c) . Calculating the distance between the true point, and the two alternative pixel positions available gives: d1 d2 = = = = y - yi m * (x+1)+b-yi yi + 1 - y yi + 1 m ( xi + 1 ) - b
Let us magically define a decision function p, to determine which distance is closer to the true point. By taking the difference between the distances, the decision function will be positive if d1 is larger, and negative otherwise. A positive scaling factor is added to ensure that no division is necessary, and only integer math need be used. pi = pi = pi = pi = where k=2 dy + dx (2b-1) dx (d1-d2) dx (2m * (xi+1) + 2b 2yi-1 ) 2 dy (xi+1) 2 dx yi + dx (2b-1 ) ------------------ (i) 2 dy xi 2 dx yi + k ------------------ (ii)
Then we can calculate pi+1 in terms of pi without any xi , yi or k . pi+1 = 2 dy xi+1 2 dx yi+1 + k = 2 dy (xi + 1) - 2 dx yi+1 + k since xi+1= xi + 1 pi+1 pi+1 = 2 dy xi + 2 dy- 2 dx yi+1 + k ------------------ (iii) Now subtracting (ii) from (iii), we get pi+1 - pi = 2 dy - 2 dx (yi+1 - yi ) pi+1 = pi + 2 dy - 2 dx (yi+1 - yi ) If the next point is: (xi+1,yi) then d1<d2 => => => d1-d2<0 pi<0 pi+1= pi + 2 dy
If the next point is: (xi+1,yi+1) then d1>d2 => => => d1-d2>0 pi>0 pi+1= pi + 2 dy - 2 dx
The pi is our decision variable, and calculated using integer arithmetic from pre-computed constants and its previous value. Now a question is remaining how to calculate initial value of pi. For that use equation (i) and put values (x1, y1) pi = 2 dy (x1+1) 2 dx yi + dx (2b-1 ) where b = y m x implies that 56 Copyright Virtual University of Pakistan
VU
pi pi pi
= = =
2 dy x1 +2 dy 2 dx yi + dx ( 2 (y1 mx1) -1 ) 2 dy x1 +2 dy 2 dx yi + 2 dx y1 2 dy x1 - dx 2 dy x1 +2 dy 2 dx yi + 2 dx y1 2 dy x1 - dx
there are certain figures will cancel each other shown in same different colour pi = 2 dy - dx
Thus Bresenham's line drawing algorithm is as follows: dx = x2-x1 dy = y2-y1 p = 2dy-dx c1 = 2dy c2 = 2(dy-dx) x = x1 y = y1 plot (x,y,colour) while (x < x2 ) x++; if (p < 0) p = p + c1 else p = p + c2 y++ plot (x,y,colour) Again, this algorithm can be easily generalized to other arrangements of the end points of the line segment, and for different ranges of the slope of the line. Improving performance Several techniques can be used to improve the performance of line-drawing procedures. These are important because line drawing is one of the fundamental primitives used by most of the other rendering applications. An improvement in the speed of line-drawing will result in an overall improvement of most graphical applications. Removing procedure calls using macros or inline code can produce improvements. Unrolling loops also may produce longer pieces of code, but these may run faster. The use of separate x and y coordinates can be discarded in favour of direct frame buffer addressing. Most algorithms can be adapted to calculate only the initial frame buffer address corresponding to the starting point and to replaced: X++ with Addr++ Y++ with Addr+=XResolution Fixed point representation allows a method for performing calculations using only integer arithmetic, but still obtaining the accuracy of floating point values. In fixed point, the fraction part of a value is stored separately, in another integer: M = Mint.Mfrac 57 Copyright Virtual University of Pakistan
VU
Mint = Mfrac =
Addition in fixed point representation occurs by adding fractional and integer components separately, and only transferring any carry-over from the fractional result to the integer result. The sequence could be implemented using the following two integer additions: ADD Yfrac,Mfrac ; ADC Yint,Mint Improved versions of these algorithms exist. For example the following variations exist on Bresenham's original algorithm: Symmetry (forward and backward simultaneously) Segmentation (divide into smaller identical segments - GCD(D x,D y) ) Double step, triple step, n step. Setting a Pixel Initial Task: Turning on a pixel (loading the frame buffer/bit-map). Assume the simplest case, i.e., an 8-bit, non-interlaced graphics system. Then each byte in the frame buffer corresponds to a pixel in the output display.
To find the address of a particular pixel (X,Y) we use the following formula: addr(X, Y) = addr(0,0) + Y rows * (Xm + 1) + X (all in bytes) addr(X,Y) = the memory address of pixel (X,Y) addr(0,0) = the memory address of the initial pixel (0,0) Number of rows = number of raster lines. Number of columns = number of pixels/raster line. Example: For a system with 640 480 pixel resolution, find the address of pixel X = 340, Y = 150 addr(340, 150) = addr(0,0) + 150 * 640 (bytes/row) + 340 = base + 96,340 is the byte location Graphics system usually have a command such as set_pixel (x, y) where x, y are integers.
VU
Lecture No.6
Circle
A circle is the set of points in a plane that are equidistant from a given point O. The distance r from the center is called the radius, and the point O is called the center. Twice the radius is . The angle a circle subtends known as the diameter from its center is a full angle, equal to 360 or radians. A circle has the maximum possible area for a given perimeter, and the minimum possible perimeter for a given area. The perimeter C of a circle is called the circumference, and is given by C=2r
Circle Drawing Techniques First of all for circle drawing we need to know what the input will be. Well the input will be one center point (x, y) and radius r. Therefore, using these two inputs there are a number of ways to draw a circle. They involve understanding level very simple to complex and reversely time complexity inefficient to efficient. We see them one by one giving comparative study. Circle drawing using Cartesian coordinates This technique uses the equation for a circle on radius r centered at (0, 0) given as: x2 + y2 = r2, an obvious choice is to plot y=
Obviously in most of the cases the circle is not centered at (0, 0), rather there is a center point (xc, yc); other than (0, 0). Therefore the equation of the circle having center at point (xc, yc): (x- xc) 2 + (y-yc)2 = r2, this implies that , y = yc Using above equation a circle can easily be drawn. The value of x varies from r-xc to r+xc. and y will be calculated using above formula. Using this technique a simple algorithm will be: Circle1 (xcenter, ycenter, radius) for x = radius - xcenter to radius + xcenter 59 Copyright Virtual University of Pakistan
VU
y = xc + drawPixel (x, y) y = xc drawPixel (x, y) This works, but is inefficient because of the multiplications and square root operations. It also creates large gaps in the circle for values of x close to r as shown in the above figure.
Circle drawing using Polar coordinates A better approach, to eliminate unequal spacing as shown in above figure is to calculate points along the circular boundary using polar coordinates r and . Expressing the circle equation in parametric polar form yields the pair of equations x = xc + r cos y = yc + r sin Using above equation circle can be plotted by calculating x and y coordinates as takes values from 0 to 360 degrees or 0 to 2. The step size chosen for depends on the application and the display device. Larger angular separations along the circumference can be connected with straight-line segments to approximate the circular path. For a more continuous boundary on a raster display, we can set the step size at 1/r. This plots pixel positions that are approximately one unit apart. Now let us see how this technique can be sum up in algorithmic form. Circle2 (xcenter, ycenter, radius) for = 0 to 2 step 1/r x = xc + r * cos y = yc + r * sin drawPixel (x, y) Again this is very simple technique and also solves problem of unequal space but unfortunately this technique is still inefficient in terms of calculations involves especially floating point calculations. Calculations can be reduced by considering the symmetry of circles. The shape of circle is similar in each quadrant. We can generate the circle section in the second quadrant of the xy-plane by noting that the two circle sections are symmetric with respect to the y axis and circle sections in the third an fourth quadrants can be obtained from sections in the first and second quadrants by considering symmetry about the x axis. We can take this one step further and note that there is also symmetry between octants. Circle sections in adjacent octants within one quadrant are symmetric with respect to the 45o line dividing the two octants. These symmetry conditions are illustrated in above figure. 60 Copyright Virtual University of Pakistan
VU
Therefore above algorithm can be optimized by using symmetric octants. Lets see: Circle2 (xcenter, ycenter, radius) for = 0 to / 4 step 1/r x = xc + r * cos y = yc + r * sin DrawSymmetricPoints (xcenter, ycenter, x, y) DrawSymmeticPoints (xcenter, ycenter, x, y) Plot ( x + xcenter, y + ycenter ) Plot ( y + xcenter, x + ycenter ) Plot ( y + xcenter, -x + ycenter ) Plot ( x + xcenter, -y + ycenter ) Plot ( -x + xcenter, -y + ycenter) Plot ( -y + xcenter, -x + ycenter) Plot ( -y + xcenter, x + ycenter) Plot ( -x + xcenter, y + ycenter)
Hence we have reduced half the calculations by considering symmetric octants of the circle but as we discussed earlier inefficiency is still there and that is due to the use of floating point calculations. In next algorithm we will try to remove this problem. Midpoint circle Algorithm As in the Bresenham line drawing algorithm we derive a decision parameter that helps us to determine whether or not to increment in the y coordinate against increment of x coordinate or vice versa for slope > 1. Similarly here we will try to derive decision parameter which can give us closest pixel position. 2 2 2 Let us consider only the first octant of a circle of x +y -r =0 x=y radius r centred on the origin. We begin by plotting point (r, 0) and end when x < y. The decision at each step is whether to choose the pixel directly above the current pixel or the pixel; which is above and to the left (8-way stepping). Assume: Pi = (xi, yi) Ti = (xi, yi +1) Si = (xi -1, yi +1)
is the current pixel. is the pixel directly above is the pixel above and to the left.
To apply the midpoint method, we define a circle function: fcircle(x, y) = x2 + y2 r2 Therefore following relations can be observed: 61 Copyright Virtual University of Pakistan
VU
f circle (x, y)
< 0, = 0, > 0,
if (x, y) is inside the circle boundary if (x, y) is on the circle boundary if (x, y) is outside the circle boundary
Yk The circle function tests given above are performed for the X2+Y2-r2=0 midpoints between pixels near the circle path at each Yk-1 sampling step. Thus, the circle function is the decision parameter in the midpoint algorithm, and we can set up incremental calculations for this function as we did in the line algorithm. Xk Xk+1 Figure given above shows the midpoint between the two candidate pixels at sampling position xk+1. Assuming we have just plotted the pixel at (xk, yk), we next need to determine whether the pixel at position (xk + 1, yk), we next need to determine whether the pixel at position (xk+1, yk) or the one at position (xk+1, yk-1) is closer to the circle. Our decision parameter is the circle function evaluated at the midpoint between these two pixels: Pk = f circle ( xk + 1, yk - ) Pk = ( xk + 1 ) 2 + ( yk - ) 2 r 2
( 1 )
If pk < 0, this midpoint is inside the circle and the pixel on scan line yk is closer to the circle boundary. Otherwise, the mid position is outside or on the circle boundary, and we select the pixel on scan-line yk-1. Successive decision parameters are obtained using incremental calculations. We obtain a recursive expression for the next decision parameter by evaluating the circle function at sampling position xk+2= xk+1+1=xk+1+1 = xk+2: Pk+1 = f circle ( xk+1 + 1, yk+1 - ) Pk+1 = [ ( xk + 1 ) + 1 ] 2 + ( yk+1 - ) 2 r 2( 2 ) Subtracting (1) from (2), we get
2
r or
Where yk+1 is either yk or yk-1, depending on the sign of Pk. Therefore, if Pk < 0 or negative then yk+1 will be yk and the formula to calculate Pk+1 will be: Pk+1 = Pk + 2( xk + 1 ) + ( y2k - y2k ) ( yk - yk ) + 1 Pk+1 = Pk + 2( xk + 1 ) + 1 Otherwise, if Pk > 0 or positive then yk+1 will be yk-1and the formula to calculate Pk+1 will be: Pk+1 = Pk + 2( xk + 1 ) + [ (y k -1)2 - y2k ] ( yk -1- yk ) + 1 Pk+1 = Pk + 2( xk + 1 ) + (y2 k - 2 y k +1 - y2k ] ( yk -1- yk ) + 1 62 Copyright Virtual University of Pakistan
VU
Pk+1 = Pk + 2( xk + 1 ) - 2 y k + 1 + 1 +1 Pk+1 = Pk + 2( xk + 1 ) - 2 y k + 2 +1 Pk+1 = Pk + 2( xk + 1 ) - 2 ( y k 1 ) + 1 Now a similar case that we observe in line algorithm is that how would starting Pk be evaluated. For this at the start pixel position will be ( 0, r ). Therefore, putting this value is equation , we get P0 = ( 0 + 1 ) 2 + ( r - ) 2 r 2 P 0 = 1 + r2 - r + r 2 P0 = 5/4 r If radius r is specified as an integer, we can simply round p0 to: P0 = 1 r Since all increments are integer. Finally sum up all in the algorithm: MidpointCircle (xcenter, ycenter, radius) y = r; x = 0; p = 1 - r; do DrawSymmetricPoints (xcenter, ycenter, x, y) x=x+1 If p < 0 Then p=p+2*(x+1)+1 else y=y-1 p=p+2*(x+1)2*(y -1)+1 while ( x < y ) Now let us consider an example to calculate first octant of the circle using above algorithm; while one quarter is displayed where you can observe that exact circle is passing between the points calculated in a raster circle. Example: xcenter= 0 ycenter= 0 radius= 10 p -9 -6 -1 6 -3 8 5 6 x 0 1 2 3 4 5 6 7 Y 10 10 10 10 9 9 8 7 63 Copyright Virtual University of Pakistan
VU
Lecture No.7
Ellipse
An ellipse is a curve that is the locus of all points in the plane the sum of whose distances r1 and r2 from two fixed points F1 and F2, (the foci) separated by a distance of is a given positive constant . This results in the two-center bipolar coordinate equation: r1 + r2 = 2a where a is the semi-major axis and the origin of the coordinate system is at one of the foci. The corresponding parameter b is known as the semiminor axis. The ellipse was first studied by Menaechmus, investigated by Euclid, and named by Apollonius. The focus and conic section directrix of an ellipse were considered by Pappus. In 1602, Kepler believed that the orbit of Mars was oval; he later discovered that it was an ellipse with the Sun at one focus. In fact, Kepler introduced the word "focus" and published his discovery in 1609. In 1705 Halley showed that the comet now named after him moved in an elliptical orbit around the Sun (MacTutor Archive). An ellipse rotated about its minor axis gives an oblate spheroid, while an ellipse rotated about its major axis gives a prolate spheroid. Let an ellipse lie along the x-axis and find the equation of the figure given above where F1 and F2 are at (-c, 0) and (c, 0). In Cartesian coordinates,
Bring the second term to the right side and square both sides,
Square one final time to clear the remaining square root, 64 Copyright Virtual University of Pakistan
VU
The parameter b is called the semi-minor axis by analogy with the parameter a, which is called the semi-major axis (assuming b < a). The fact that b as defined at right is actually the semi-minor axis is easily shown by letting r1 and r2 be equal. Then two right triangles are produced, each with hypotenuse a, base c, and height b = a2 - c2. Since the largest distance along the minor axis will be achieved at this point, b is indeed the semi-minor axis. If, instead of being centered at (0, 0), the center of the ellipse is at (x0, y0), at right equation becomes:
Ellipse Drawing Techniques Now we already understand circle drawing techniques. One way to draw ellipse is to use the following equation:
where x0 may be replaced by xc in case of center other than origin and same in case of y. Another way is to use polar coordinates r and , for that we have parametric equations: 65 Copyright Virtual University of Pakistan
VU
x = xc + rx cos y = yc + ry sin Four-way symmetry Symmetric considerations can be had to further reduce computations. An ellipse in standard position is symmetric between quadrants, but unlike a circle, it is not symmetric between the two octants of a quadrant. Thus, we must calculate pixel positions along the elliptical arc throughout one quadrant, and then we obtain positions in the remaining three quadrants by symmetry as shown in at right figure. Midpoint ellipse algorithm Consider an ellipse centered at the origin:
To apply the midpoint method, we define an ellipse function: f ellipse (x, y) = ry2x2 + rx2y2 rx2 ry2 Therefore following relations can be observed: < 0, = 0, > 0, if (x, y) is inside the circle boundary if (x, y) is on the circle boundary if (x, y) is outside the circle boundary
f ellipse (x, y)
Now as you have some idea that ellipse is different from circle. Therefore, a similar approach that is applied in circle can be applied here using some different sampling direction as shown in the figure at right. There are two regions separated in one octant. Therefore, idea is that in region 1 sampling will be at x direction; whereas y coordinate will be related to decision parameter. In region 2 sampling will be at y direction; whereas x coordinate will be related to decision parameter. So consider first region 1. We will start at (0, r y); we take unit steps in the x direction until we reach the boundary between region 1 and region 2. Then we switch to unit steps in the y direction over the remainder of the curve in the first quadrant. At each step, we 66 Copyright Virtual University of Pakistan
VU
need to test the value of the slope of the curve. The ellipse slope is calculated from following equation: dy / dx = -2 ry2x2 / 2 rx2y2 At the boundary region 1 and region 2, dy/ dx = -1 and 2 rx2y2 = 2 ry2x2 Therefore, we move out of region 1 whenever 2 ry2x2 >= 2 rx2y2 Figure at right shows the midpoint between the two candidate pixels at sampling position xk + 1 in the first region. Assuming position (xk, yk) has been selected at the previous step; we determine the next position along the ellipse path by evaluating the decision parameter at this midpoint: P1k = f ellipse ( xk + 1, yk ) f ellipse (xk +1, yk ) = r2y ( xk + 1)2 + rx2 ( yk )2 rx2 ry2 -------( 1 ) If pk < 0, this midpoint is inside the ellipse and the pixel on scan line yk is closer to the ellipse boundary. Otherwise, the mid position is outside or on the ellipse boundary, and we select the pixel on scan-line yk-1. Successive decision parameters are obtained using incremental calculations. We obtain a recursive expression for the next decision parameter by evaluating the ellipse function at sampling position xk+1=xk+2: fellipse (xk+1 +1, yk+1 ) = ry2 [( xk + 1) + 1 ] 2 + rx2 ( yk+1 ) 2 rx2 ry2 ---( 2 ) Subtracting (1) from (2), and by simplification, we get Pk+11 = Pk1 + 2 ry2 ( xk + 1) + rx2 ( yk+12 yk2 ) - rx2 (yk+1 - yk ) + ry2 Where yk+1 is either yk or yk-1, depending on the sign of Pk. Therefore, if Pk < 0 or negative then yk+1 will be yk and the formula to calculate Pk+1 will be: P1k+1 = Pk1 + 2 ry2 ( xk + 1) + rx2 ( y k2 yk2 ) - rx2 (yk - yk ) + ry2 Pk+11 = Pk1 + 2 ry2 ( xk + 1 ) + ry2 Otherwise, if Pk > 0 or positive then yk+1 will be yk-1and the formula to calculate Pk+1 will be:
VU
Pk+11 = Pk1 + 2 ry2 ( xk + 1) + r2x ( (yk 1)2 yk2 ) - rx2 (yk 1 yk ) + ry2 P1k+1 = P1k + 2 r y 2 ( x k + 1) + r x 2 ( 2 y k + 1 ) - r x 2 ( 1 ) + r y 2 P1k+1 = P1k + 2 ry2 ( x k + 1) 2 rx2 y k + r2x + rx2 + ry2 P1k+1 = P1k + 2 r y2 ( x k + 1) 2 r x2 ( y k 1 ) + r y2 Now a similar case that we observe in line algorithm is from where starting Pk will evaluate. For this at the start pixel position will by ( 0, ry ). Therefore, putting this value is equation , we get P10 = r y2 ( 0 + 1) 2 + r x2 (ry ) 2 rx2 ry2 P10 = r2y + rx2 ry2 r2x ry + rx2 rx2 ry2 P10 = r2y rx2 r y + rx2 Similarly same procedure will be adapted for region 2 and decision parameter will be calculated, here we are giving decision parameter and there derivation is left as an exercise for the students. Pk+12 = Pk2 2 rx2 ( yk + 1 ) + rx2 if pk2 > 0 ,
Pk+12 = Pk2 + 2 ry2 ( xk + 1) 2 rx2 yk + rx2 otherwise The initial parameter for region 2 will be calculated by following formula using the last point calculated in region 1 as: P02 = ry2 (x0 + ) + rx2 (y0 - 1 )2 rx2ry2 Since all increments are integer. Finally sum up all in the algorithm: MidpointEllipse (xcenter, ycenter, r x, r y) x =0 x =0 y = ry do DrawSymmetricPoints (xcenter, ycenter, x, y) P01 = ry2 rx2 ry + rx2 x = x +1 If p1k < 0 Pk+11 = Pk1 + 2 ry2 ( xk + 1 ) + ry2 else Pk+11 = Pk1 + 2 ry2 ( xk + 1) 2 rx2 ( yk 1 ) + r2y y = y -1 P02 = ry2 (x 0 + ) + rx2 (y 0 - 1 )2 rx2 ry2 If p2k > 0 y = y -1
VU
Pk+12 = Pk2 2 rx2 ( yk + 1 ) + rx2 else Pk+12 = Pk2 + 2 ry2 ( xk + 1) 2 rx2 yk + rx2 while ( 2 ry2x2 >= 2 rx2y2 )
x=x+1
Other Curves Various curve functions are useful in object modeling, animation path specifications, data, function graphing, and other graphics applications. Commonly encountered curves include conics, trigonometric and exponential functions, probability distributions, general polynomials, and spline functions. Displays of these curves can be generated with methods similar to those discussed for the circle and ellipse. We can obtain positions along curve paths directly from explicit representations y = f(x) or from parametric forms. Alternatively, we could apply the incremental midpoint method to plot curves described with implicit functions f(x,y) = 0. Conic Sections A conic section is the intersection of a plane and a cone. Circle Ellipse (h)Parabola (h)Hyperbola (h)
Ellipse
(v)Parabola
(v)Hyperbola
(v)
The type of section can be found from the sign of: B2-4AC If B2 - 4AC is then the curve is a... < 0 ellipse, circle, point or no curve. = 0 parabola, 2 parallel lines, 1 line or no curve. > 0 hyperbola or 2 intersecting lines. For any of the below with a center (j, k) instead of (0, 0), replace each x term with (x-j) and each y term with (y-k).
VU
Circle
Ellipse
2 2 2 2
Parabola
Hyperbola
(horiz. of (vert. of
x2 + y2 = r2
x /a +y /b 4px = y2 =1
x2 / a2 - y2 / b2 = 1 y = (b/a)x
x2 + y2 = r2
y2 / a2 + x2 / b2 4py = x2 =1
y2 / a2 - x2 / b2 = 1 x = (b/a)y
Variables:
a = major radius (= 1/2 length major axis) r = circle b = minor radius radius (= 1/2 length minor axis) c = distance center to focus 0 p=0 a -b =c
2 2 2
a = 1/2 length major axis b = 1/2 length minor axis c = distance center to focus
c/a p=p
c/a a2 + b2 = c2
Definition: is the sum of distance to distance to difference between locus of all points distances to the origin is focus = distance distances to each which meet the each focus is constant to directrix foci is constant condition... constant
Hyperbola
We begin this section with the definition of a hyperbola. A hyperbola is the set of all points (x, y) in the plane the difference of whose distances from two fixed points is some constant. The two fixed points are called the foci. Each hyperbola consists of two branches. The line segment; which connects the two foci intersects the hyperbola at two points, called the vertices. The line segment; which ends at these vertices is called the transverse axis and the midpoint of this line is called the center of the hyperbola. See figure at right for a sketch of a hyperbola with these pieces identified. Note that, as in the case of the ellipse, a hyperbola can have a vertical or horizontal orientation. We now turn our attention to the standard equation of a hyperbola. We say that the standard equation of a hyperbola centered at the origin is given by 70 Copyright Virtual University of Pakistan Focus
VU
if the transverse axis is vertical. Notice a very important difference in the notation of the equation of a hyperbola compared to that of the ellipse. We see that a always corresponds to the positive term in the equation of the ellipse. The relationship of a and b does not determine the orientation of the hyperbola. (Recall that the size of a and b was used in the section on the ellipse to determine the orientation of the ellipse.) In the case of the hyperbola, the variable in the ``positive'' term of the equation determines the orientation of the hyperbola. Hence, if the variable x is in the positive term of the equation, as it is in the equation
Note that the vertices are always a units from the center of the hyperbola, and the distance c of the foci from the center of the hyperbola can be determined using a, b, and the following equality:
We will use this relationship often, so keep it in mind. The next question you might ask is this: ``what happens to the equation if the center of the hyperbola is not (0, 0)?'' As in the case of the ellipse, if the center of the hyperbola is (h, k), then the equation of the hyperbola becomes
VU
if the transverse axis is vertical. A few more terms should be mentioned here before we move to some examples. First, as in the case of an ellipse, we say that the eccentricity of a hyperbola, denoted by e, is given by
or we say that the eccentricity of a hyperbola is given by the ratio of the distance between the foci to the distance between the vertices. Now in the case of a hyperbola, the distance between the foci is greater than the distance between the vertices. Hence, in the case of a hyperbola,
Two final terms that we must mention are asymptotes and the conjugate axis. The two branches of a hyperbola are bounded by two straight lines, known as asymptotes. These asymptotes are easily drawn once one plots the vertices and the points (h, k+b) and (h, k-b) and draws the rectangle which goes through these four points. The line segment joining (h, k+b) and (h, k-b) is called the conjugate axis. The asymptotes then are simply the lines which go through the corners of the rectangle. But what are the actual equations of these asymptotes? Note that if the hyperbola is oriented horizontally, then the corners of this rectangle have the following coordinates:
and
Here I have paired these points in such a way that each asymptote goes through one pair of the points. Consider the first pair of points:
Given two points, we can find the equation of the unique line going through the points using the point--slope form of the line. First, let us determine the slope of our line. We 72 Copyright Virtual University of Pakistan
VU
find this as ``change in y over change in x'' or ``rise over run''. In this case, we see that this slope is equal to
or simply
Then, we also know that the line goes through the center (h, k). Hence, by the point-slope form of a line, we know that the equation of this asymptote is
or
The other asymptote in this case has a negative slope; which is given by
Using the same argument, we see that this asymptote has equation
What if the hyperbola is vertically oriented? Then one of the asymptote will go through the corners of the rectangle given by
Then the slope in this case will not be b/a but will be a/b. Hence, analogous to the work we just performed, we can show that the asymptotes of a vertically oriented hyperbola are determined by
and
Parabola
A parabola is the set of all points (x, y) that are the same distance from a fixed line (called the directrix) and a fixed point (focus) not on the directrix. See figure for the view of a parabola and its related focus and directrix. 73 Copyright Virtual University of Pakistan
VU
Note that the graph of a parabola is similar to one branch of a hyperbola. However, you should realize that a parabola is not simply one branch of a hyperbola. Indeed, the branches of a hyperbola approach linear asymptotes, while a parabola does not do so. Several other terms exist which are associated with a parabola. The midpoint between the focus and directrix of the parabola is called the vertex and the line passing through the focus and vertex is called the axis of the parabola. (This is similar to the major axis of the ellipse and the transverse axis of the hyperbola.) See figure at right.
Now let's move to the standard algebraic equations for parabolas and note the four types of parabolas that exist. As we discuss the four types, you should notice the differences in the equations that are related to each of the four parabolas. The standard form of the equation of the parabola with vertex at (0, 0) with the focus lying d units from the vertex is given by
if the axis is horizontal. See figure below for an example with vertical axis and figure below for an example with horizontal axis.
VU
It is also the case that d could be negative, which flips the orientation of the parabola. (See Figures) Thus, we see that there are four different orientations of parabolas, which depend on a) which variable is squared (x or y) and b) whether d is positive or negative. One last comment before going to some examples; if the vertex of the parabola is at (h, k), then the equation of the parabola does change slightly. The equation of a parabola with vertex at (h, k) is given by
Rotation of Axes
Note that in the sections at right dealing with the ellipse, hyperbola, and the parabola, the algebraic equations that appeared did not contain a term of the form xy. However, in our Algebraic View of the Conic Sections,'' we stated that every conic section is of the form
where A, B, C, D, E, and F are constants. In essence, all of the equations that we have studied have had B=0. So the question arises: ``what role, if any, does the xy term play in conic sections? If it were present, how would that change the geometric figure?'' First of all, the answer is NOT that the conic changes from one type to another. That is to say, if we introduce a xy term, the conic does NOT change from an ellipse to a hyperbola. If we start with the standard equation of an ellipse and insert an extra term, a xy term, we still have an ellipse.
v y g
So what does the xy term do? The xy term actually rotates the graph in the plane. For example, in the case of an ellipse, the major axis is no longer parallel to the x-axis or y-axis. Rather, depending on the constant in front of the xy term, we now have the major axis rotated.
Animated Applications Ellipses, hyperbolas, and parabolas are particularly useful in certain animation applications. These curves describe orbital and other motions for objects subjected to gravitational, electromagnetic, or nuclear forces. Planetary orbits in the solar system, for
VU
example, are ellipses; and an object projected into a uniform gravitational field travels along a parabolic trajectory. Figure at right shows a parabolic path in standard position for gravitational field acting in the negative y direction. The explicit equation for the parabolic trajectory of the object shown can be written as: y = y0 + a (x - x0 )2 + b ( x - x0 ) With constants a and b determined by the initial velocity v0 of the object and the acceleration g due to the uniform gravitational force. We can also describe such parabolic motions with parametric equations using a time parameter t, measured in seconds from the initial projection point: x = x0 + vx0 t y = y0 + vy0 t g t 2 Here vx0 and vy0 are the initial velocity components, and the value of g near the surface of the earth is approximately 980 cm/ sec2. Object positions along the parabolic path are then calculated at selected time steps.
Some related real world applications are given below. Parabolic Reflectors
One of the ``real--world'' applications of parabolas involves the concept of a 3-dimensional parabolic reflector in which a parabola is revolved about its axis (the line segment joining the vertex and focus). The shape of car headlights, mirrors in reflecting telescopes, and television and radio antennae (such as the one at right) all utilize this property. In terms of a car headlight, this property is used to reflect the light rays emanating from the focus of the parabola (where the actual light bulb is located) in parallel rays. This property is used in a converse fashion when one considers parabolic antennae. Here, all incoming rays parallel to the axis of the parabola are reflected through the focus.
Elliptical Orbits
At one time, it was thought that the planets in our solar system revolve around the sun in a circular 76 Copyright Virtual University of Pakistan
VU
orbit. It was later discovered, however, that the orbits are not circular, but were actually very round elliptical shapes. (Recall the discussion of the eccentricity of an ellipse mentioned at right.) The eccentricity of the orbit of the Earth around the sun is approximately 0.0167, a fairly small number. Pluto's orbit has the highest eccentricity of all the planets in our solar system at 0.2481. Still, this is not a very large value. As a matter of fact, the sun acts as one of the foci in the ellipse. This phenomenon was first noted by Apollonius in the second century B.C. Kepler later studied this in a more rigorous fashion and developed the scientific view of planetary motion.
Whispering Galleries
In rooms whose ceilings are elliptical, a sound made at one focus of the ellipse will be reflected to the other focus (across the room), allowing people standing at the two foci to hear one another very clearly. This has been called the ``whispering gallery'' effect and has been used by many in the design of special rooms. In particular, St. Paul's Cathedral and one of the rooms at the United States Capitol were built with this in mind.
Polynomials and Spline Curves A polynomial function of nth degree in x is defined as
y =
a kx k
y = a 0 x 0 + a 1 x 1 + ----------------+ a n-1 x n-1 + a n x n Where n is a nonnegative integer and the a k are constants, with a n not equal to 0. We get a quadratic when n = 2; a cubic polynomial when n = 3; a quadratic when n = 4; and so forth. And obviously a straight line when n = 1. Polynomials are useful in a number of graphics applications, including the design of object shapes, the specifications of animation paths, and the graphing of data trends in a discrete set of data points. Designing object shapes or motion paths is typically done by specifying a few points to define the general curve contour, then fitting the selected points with a polynomial. One way to accomplish the curve fitting is to construct a cubic polynomial curve section between each pair of specified points. Each curve section is then described in parametric form as x = a x0 + a x1 u + a x2 u 2 + a x3 u 3 y = a y0 + a y1 u + a y2 u 2 + a y3 u 3 Where parameter u varies over the interval 0 to1. A curve is shown below calculated using at right equations.
Continuous curves that are formed with polynomial pieces are called spline curves, or simply splines. Spline is a detailed topic; which will be discussed later in 3 dimensions. 77 Copyright Virtual University of Pakistan
8-Filled-Area Primitives-I
VU
Lecture No.8
Filled-Area Primitives-I
So far we have covered some output primitives that is drawing primitives like point, line, circle, ellipse and some other variations of curves. Also we can draw certain other shapes with the combinations of lines like triangle, rectangle, square and other polygons (we will have some discussion on polygons coming ahead). Also we can draw some shapes using mixture of lines and curves or circles etc. So we are able to draw outline/ sketch of certain models but need is there to make a solid model. Therefore, in this section we will see what are filled area primitives and what are the different issues related to them. There are two basic approaches to area filling on raster systems. One way is to draw straight lines between the edges of polygon called scan-line polygon filling. As said earlier there are several issues related to scan line polygon, which we will discuss in detail. Second way is to start from an interior point and paint outward from this point till we reach the boundary called boundary-fill. A slight variation of this technique is used to fill an area specified by cluster (having no specific boundary). The technique is called flood-fill and having almost same strategy that is to start from an interior point and start painting outward from this point till the end of cluster. Now having an idea we will try to see each of these one by one, starting from scan-line polygon filling.
Scan-line Polygon Fill
Before we actually start discussion on scan-line polygon filling technique, it is useful to discuss what is polygon? Besides polygon definition we will discuss the following topics one by one to have a good understanding of the concept and its implementation.