CSCI 4620/8626. Primitives and Attributes

Similar documents
Computer Graphics. Chapter 4 Attributes of Graphics Primitives. Somsak Walairacht, Computer Engineering, KMITL 1

Computer Graphics. Attributes of Graphics Primitives. Somsak Walairacht, Computer Engineering, KMITL 1

Graphics (Output) Primitives. Chapters 3 & 4

UNIVERSITY OF NEBRASKA AT OMAHA Computer Science 4620/8626 Computer Graphics Spring 2014 Homework Set 1 Suggested Answers

CS 543: Computer Graphics. Rasterization

Chapter 3. Sukhwinder Singh

COMP371 COMPUTER GRAPHICS

Unit 2 Output Primitives and their Attributes

Rasterization, or What is glbegin(gl_lines) really doing?

Filled Area Primitives. CEng 477 Introduction to Computer Graphics METU, 2007

2D rendering takes a photo of the 2D scene with a virtual camera that selects an axis aligned rectangle from the scene. The photograph is placed into

Einführung in Visual Computing

ERKELEY DAVIS IRVINE LOS ANGELES RIVERSIDE SAN DIEGO SAN FRANCISCO EECS 104. Fundamentals of Computer Graphics. OpenGL

Chapter 8: Implementation- Clipping and Rasterization

CSCI 4620/8626. Computer Graphics Attributes of Graphics Primitives (Chapter 5)

Polygon Filling. Can write frame buffer one word at time rather than one bit. 2/3/2000 CS 4/57101 Lecture 6 1

CSCI 4620/8626. Coordinate Reference Frames

CS602 Midterm Subjective Solved with Reference By WELL WISHER (Aqua Leo)

Buffers, Textures, Compositing, and Blending. Overview. Buffers. David Carr Virtual Environments, Fundamentals Spring 2005 Based on Slides by E.

Lets assume each object has a defined colour. Hence our illumination model is looks unrealistic.

Rasterization: Geometric Primitives

Computer Graphics (CS 543) Lecture 10: Rasterization and Antialiasing

Topic #1: Rasterization (Scan Conversion)

COMP30019 Graphics and Interaction Scan Converting Polygons and Lines

Discrete Techniques. 11 th Week, Define a buffer by its spatial resolution (n m) and its depth (or precision) k, the number of

Computer Graphics. - Rasterization - Philipp Slusallek

Shading Techniques Denbigh Starkey

CSCI 4620/8626. Computer Graphics Clipping Algorithms (Chapter 8-5 )

CS 325 Computer Graphics

Line Drawing. Introduction to Computer Graphics Torsten Möller / Mike Phillips. Machiraju/Zhang/Möller

Line Drawing. Foundations of Computer Graphics Torsten Möller

(Refer Slide Time: 00:02:00)

Chapter - 2: Geometry and Line Generations

Renderer Implementation: Basics and Clipping. Overview. Preliminaries. David Carr Virtual Environments, Fundamentals Spring 2005

Fall CSCI 420: Computer Graphics. 7.1 Rasterization. Hao Li.

The Traditional Graphics Pipeline

The Traditional Graphics Pipeline

Rasterization and Graphics Hardware. Not just about fancy 3D! Rendering/Rasterization. The simplest case: Points. When do we care?

Pipeline implementation II

EECE 478. Learning Objectives. Learning Objectives. Rasterization & Scenes. Rasterization. Compositing

CMSC 425: Lecture 4 More about OpenGL and GLUT Tuesday, Feb 5, 2013

CS488 2D Graphics. Luc RENAMBOT

Attributes of Graphics Primitives

CSCI 420 Computer Graphics Lecture 14. Rasterization. Scan Conversion Antialiasing [Angel Ch. 6] Jernej Barbic University of Southern California

FROM VERTICES TO FRAGMENTS. Lecture 5 Comp3080 Computer Graphics HKBU

Agenda. Polygon Terminology Types of polygons Inside Test Polygon Filling Algorithms. Scan-Line Polygon Fill Algorithm Flood-Fill Algorithm

Adobe Photoshop Sh S.K. Sublania and Sh. Naresh Chand

? Which intermediate. Recall: Line drawing algorithm. Programmer specifies (x,y) of end pixels Need algorithm to determine pixels on line path

Rasterization. Rasterization (scan conversion) Digital Differential Analyzer (DDA) Rasterizing a line. Digital Differential Analyzer (DDA)

CS 4731/543: Computer Graphics Lecture 7 (Part I): Raster Graphics: Polygons & Antialiasing. Emmanuel Agu

Rasterization Computer Graphics I Lecture 14. Scan Conversion Antialiasing Compositing [Angel, Ch , ]

The Traditional Graphics Pipeline

GL_COLOR_BUFFER_BIT, GL_PROJECTION, GL_MODELVIEW

Graphics Programming

2D Graphics Primitives II. Additional issues in scan converting lines. 1)Endpoint order. Want algorithms to draw the same pixels for each line

Tópicos de Computação Gráfica Topics in Computer Graphics 10509: Doutoramento em Engenharia Informática. Chap. 2 Rasterization.

Incremental Form. Idea. More efficient if we look at d k, the value of the decision variable at x = k

3. Raster Algorithms. 3.1 Raster Displays. (see Chapter 1 of the Notes) CRT LCD. CS Dept, Univ of Kentucky

Building Models. Prof. George Wolberg Dept. of Computer Science City College of New York

Rendering. Converting a 3D scene to a 2D image. Camera. Light. Rendering. View Plane

CS 130 Final. Fall 2015

4.5 VISIBLE SURFACE DETECTION METHODES

Image Processing. Alpha Channel. Blending. Image Compositing. Blending Errors. Blending in OpenGL

OpenGL Graphics System. 2D Graphics Primitives. Drawing 2D Graphics Primitives. 2D Graphics Primitives. Mathematical 2D Primitives.

Display Technologies: CRTs Raster Displays

0. Introduction: What is Computer Graphics? 1. Basics of scan conversion (line drawing) 2. Representing 2D curves

Raster Scan Displays. Framebuffer (Black and White)

Graphics Hardware and Display Devices

UNIT 2 GRAPHIC PRIMITIVES

graphics pipeline computer graphics graphics pipeline 2009 fabio pellacini 1

Implementation III. Ed Angel Professor of Computer Science, Electrical and Computer Engineering, and Media Arts University of New Mexico

graphics pipeline computer graphics graphics pipeline 2009 fabio pellacini 1

Image Processing. CSCI 420 Computer Graphics Lecture 22

8. Hidden Surface Elimination

From Vertices to Fragments: Rasterization. Reading Assignment: Chapter 7. Special memory where pixel colors are stored.

CHAPTER 1 Graphics Systems and Models 3

Lectures Transparency Case Study

Computer Graphics Lecture Notes

How to draw and create shapes

Computer Graphics Fundamentals. Jon Macey

OpenGL. Jimmy Johansson Norrköping Visualization and Interaction Studio Linköping University

03 Vector Graphics. Multimedia Systems. 2D and 3D Graphics, Transformations

Today s Agenda. Basic design of a graphics system. Introduction to OpenGL

Scan Conversion- Polygons

Scan line algorithm. Jacobs University Visualization and Computer Graphics Lab : Graphics and Visualization 272

CSE 167: Introduction to Computer Graphics Lecture #5: Rasterization. Jürgen P. Schulze, Ph.D. University of California, San Diego Fall Quarter 2015

Lecture 3: Art Gallery Problems and Polygon Triangulation

R asterisation. Part I: Simple Lines. Affine transformation. Transform Render. Rasterisation Line Rasterisation 2/16

Chapter 3. Texture mapping. Learning Goals: Assignment Lab 3: Implement a single program, which fulfills the requirements:

E.Order of Operations

Computer Graphics. Making Pictures. Computer Graphics CSC470 1

Text in OpenGL and Windows. Computer Graphics Attributes. Computer Graphics. Binghamton University. EngiNet. Thomas J. Watson

Reading on the Accumulation Buffer: Motion Blur, Anti-Aliasing, and Depth of Field

Basic Graphics Programming

Class of Algorithms. Visible Surface Determination. Back Face Culling Test. Back Face Culling: Object Space v. Back Face Culling: Object Space.

Topics. From vertices to fragments

Order Independent Transparency with Dual Depth Peeling. Louis Bavoil, Kevin Myers

Lectures OpenGL Introduction

Sign up for crits! Announcments

Pen Tool, Fill Layers, Color Range, Levels Adjustments, Magic Wand tool, and shadowing techniques

Transcription:

CSCI 4620/8626 Computer Graphics Attributes of Graphics Primitives (Chapter 5) Last update: 2016-02-23 Primitives and Attributes The graphics primitives we ve seen so far are fundamental shapes, like lines, circles, and filled areas. Each of these primitives has certain attributes, for most of which we ve accepted defaults. For example, color and size are obvious attributes of every primitive which we ve specified explicitly. Other attributes, such as whether a line is solid or dotted, thick or thin, we ve ignored to this point. 2 1

Special Condition Attributes Some attributes may apply to a primitive only under special circumstances. For example, when we consider whether a line is hidden or not, its visibility is affected. Likewise, a hidden line cannot be detected by a program that permits the selection (by a mouse, for example) of objects in the scene. 3 Specifying Parameters Different graphics packages allow parameters to be specified in various ways. Some primitive drawing commands may include parameters to control attributes. For example, a command to draw a line may include parameters specifying color, length, width, and style (solid or dashed). Other packages may use a graphics state with variables or parameters that affect all new objects. OpenGL uses this approach. 4 2

OpenGL State Variables It s easiest to think of a state as a structure that includes potentially many variables, each of which controls one feature or attribute of the graphics system. State information in OpenGL includes things like color, primitive attributes, current matrix mode, frame buffer position, and so forth. Changes to the state only affect new primitives drawn after the state change. Some state changes may appear between glbegin and glend. 5 RGB Color Components As already noted, color information can be stored directly in the frame buffer. This requires 3N bits for each pixel if N bits of color intensity are provided (for red, green, and blue). Many modern graphics systems use this scheme. Alternately, each pixel in the frame buffer may record a color number or index, which identifies a complete color entry in a color lookup table. If 2 k colors will suffice for a scene, then each pixel needs only k bits, while the color table entries can be as large as required. Usually 256 or 512 entries (k=8 or k=9) will suffice. Changing colors only requires changing the color lookup table entry; no pixel changes are needed. 6 3

Gray Scale To draw using shades of gray on an RGB system, it is only necessary to ensure that the intensity of the red, green, and blue components are the same. Values close to 0 produce dark shades of gray (close to black), while values close to 1 produce light shades of gray (close to white). 7 Other Color Parameters Color is a complex subject, and much research on color has been done. Remember, as in any form of communication, we must consider both the generator of the signal (in this case, colored light) and the receiver (e.g. the human eye). For example, the term intensity is used to refer to the physical amount of light energy generated by a source, while the term luminance is a psychological term indicating perceived brightness of the light. 8 4

glutinitdisplaymode glutinitdisplaymode (unsigned int mode) is used when creating a top-level window. The mode parameter is a bitwise or of zero or more symbolic constants, including these: GLUT_RGB or GLUT_RGBA (default) GLUT_INDEX (uses a color table) GLUT_SINGLE,GLUT_DOUBLE (how many buffers) GLUT_STEREO GLUT_ALPHA and others 9 glcolor glcolor* (colorcomponents); is used to set the color (in the state) for new primitives. As usual, * indicates the number of components and their data type. For example, 3f indicates three floating point components (red, green, blue) will be provided. When integer data is used, the values range from 0 to 2 k -1, where k is the number of bits of intensity information for each color in each pixel. 0 to 255 is a common range. 10 5

glindex glindex* (colorindex) is used instead of glcolor if a color table is used (that is, if GLUT_INDEX is specified in the display mode). The colorindex value is used to specify the color entry in the color table that should be used for new primitives. OpenGL does not provide a technique to set the color table entries, since they are part of the windowing system. 11 glutsetcolor glutsetcolor(index, red, green, blue) is used to set an entry in the color lookup table. Note that this is a glut function, and not an OpenGL function. That s because glut includes the functions that interact with a specific windowing system (e.g. MS Windows or X-11). The color parameters red, green, and blue are specified as floating point values between 0.0 and 1.0. Additional color tables are provided as extensions to the OpenGL core library for such things as setting camera focusing effects, filtering certain colors from an image, or making brightness adjustments. 12 6

Color Blending When a primitive is drawn in a region of the frame buffer that already contains information, the default is for the pixels of the new primitive to replace the pixels of the old information. This action can be modified by enabling colorblending (or image-compositing) functions. Enabling these functions (and others) in OpenGL is done with the glenable function: glenable(gl_blend); Disabling is naturally done with gldisable( ); 13 Blending Factors (1) Call the current object (the one in the frame buffer) the destination, and the new object (the one being drawn) the source. For each of the three color components (r,g,b) the resulting color intensity is a linear combination of that of the source and that of the destination, forced into the 0.0-1.0 range. Two parameters are required for each component, the multiplier for the source (S) and the multiplier for the destination (D). Then the resulting red component (R) is computed as R s * S + R d * D The other components are computed in the same manner. 14 7

Blending Factors (2) To specify the blending factors (if GL_BLEND has been enabled), use glblendfunc (sfactor, dfactor); sfactor and dfactor are each a symbolic constant specifying values for the various factors. Examples include: GL_ZERO all zeroes GL_ONE all ones GL_DST_ALPHA use the destination alpha GL_SRC_ALPHA use the source alpha See the blend demo program. 15 Color Arrays (1) Colors may be specified for a scene in combination with the vertices by enabling the color-array features of OpenGL: glenable(gl_color_array); Then the color information (location, format) is specified with: glcolorpointer (n, type, offset, array); where n is 3 or 4 (if alpha is specified), type is GL_FLOAT (for example), offset specifies the number of bytes in each entry, and array is a pointer to the array of color entries. 16 8

Color Arrays (2) Now we can construct an array containing desired color values in a manner similar to the way we constructed an array of vertices. When a rendering function that utilizes arrays for vertices (like gldrawarrays or gldrawelements) is invoked, the color information is automatically employed (if enabled). 17 Example vertexarrayptr colorarrayptr vertex1 vertex2 vertex3 vertex4 color1 color2 color3 color4 18 9

Using Fewer Arrays The vertex and color element information can be alternated in a single array by using the offset parameter. For example, suppose the first three floats are a vertex and the next three floats are the color for that vertex. Then using 6 (times the size of a float) as the offset will tell OpenGL where the vertex information can be found, starting at the beginning of the array. The color information is also found using the same offset, starting at the third float in the array. (Note the error in the 3rd edition textbook on page 181.) 19 Interlaced Arrays, in General There are other arrays that can be used in a manner similar to those for vertices and colors. OpenGL provides a general mechanism for enabling (or disabling) these arrays, for specifying which are to be used, the type of elements, and the location of the array. For example, glinterleavedarrays (GL_C3F_V3F, 0, arrayptr); could be used to indicate floating color and vertex information (only) is present at arrayptr. 20 10

glclearcolor glclearcolor(red,green,blue,alpha); is used to specify the background color (and alpha value) used when a window is created or cleared. The parameters are floating point values in the range 0.0 to 1.0. Alpha is used with color blending (when enabled). 21 glclear, glclearindex glclear(buffername(s)); is used to clear one of the color buffers, setting every pixel to the same color. The parameter is a bitwise or of one or more buffer names. GL_COLOR_BUFFER_BIT is the buffer currently enabled for color writing, and the others are the depth buffer, the stencil buffer, and the accumulation buffer. glclearindex (index); is used to set the window background to the color at the specified index. 22 11

Point Attributes Points have two attributes: color and size. For a raster system, a point size is an integer multiple of the pixel size. The function glpointsize (size); where size is a floating point value, specifies the size of a point in OpenGL. Unless anti-aliasing is enabled, the size is rounded to an integer. 23 Line Attributes Lines obviously have length and color, but they also have additional attributes of width and style. Width is a simple attribute to implement just use multiple side-by-side pixels to get a thicker line. The side-by-side pixels are in the vertical dimension if the line slope is less than 1 (as shown below), or horizontal for slopes greater than 1. 24 12

Alternate Line Width Technique Another technique that can be used to draw lines with widths larger than one pixel is to treat them as filled polygons. The coordinates of the polygon are obtained by taking the position of the ends of perpendiculars to the line path at its ends. The perpendiculars are one-half the desired line width. 25 Line End Styles The ends of lines with widths larger than one can be displayed in several common ways: Butt caps Round caps Projecting caps Similar considerations may be made when several lines meet at the same pixel. 26 13

Line Styles Line styles include solid, dashed, dotted, and variations on these. A simple way to indicate how a line should be drawn is by using a pixel mask of some number of bits. One-bits are used where the line should be visible, and zero-bits are used where the line should be transparent (or in the background color). For example, the pixel mask 0000000011111111 might be used to indicate that we want eight pixels with the foreground color, then eight with the background color. This pattern would be repeated to yield a dashed line. 27 Dashed Lines The difficulty with the simple scheme just described is that lines with different slopes will have different length dashes. For example, a 45-degree diagonal line will have visible dashes that are longer by a factor of 2 longer than a horizontal or vertical line. The obvious solution to this last problem is to alter the pixel mask appropriately for the slope of the line. 28 14

Pen and Brush Options Drawing packages frequently allow the interactive user to select a shape for the end of their drawing tool. A shapes is typically implemented as a pixel map that is then replicated along the path when the pen or brush is moved. For example, the Windows Paint program provides a variety of options for its brush. 29 Curve Attributes Curve attributes are similar to those for straight line segments: color, width, and style. Curved line width can be accommodated in a manner similar to line segments. That is, when the slope of the curve is less than one, we replicate points vertically; horizontal replication is used when the slope is greater than one. Similarly, a curved line wider than one pixel can be displayed as a filled area between two curves. 30 15

Dashed Curved Lines Dashed curved lines can be drawn using the same pixel map approach applied to straight lines. The generation of equal-length dashes is more complicated for curved lines, however, since the slope of the curved line is continuously changing. For regular curves (e.g. circles, ellipses) we can use the pixel map and angular distance instead of linear distance to general equal-length dashes. 31 gllinewidth The function call gllinewidth (w); will set the width attribute for all new lines to w, a floating point parameter, rounded to an integer. If the width rounds to 0, then a width of 1 is used. If anti-aliasing is enabled, edges are smoothed to minimize the appearance of the jaggies. Some OpenGL implementations may support only a limited number of line widths. 32 16

gllinestipple The function call gllinestipple (repeatfactor, pattern); is used to specify a dotted or dashed line style. Pattern is a 16-bit integer used as a pixmap, with the low-order bit used first. repeatfactor indicates how many times each bit is to be repeated before moving on to the next bit. For polylines, the pattern is not restarted at the beginning of each segment, but is instead continued. GL_LINE_STIPPLE must be enabled usingglenable. See the stipple demo program. 33 glshademodel Shading that is, changing colors of a primitive depending on the position in the primitive is enabled by default, just as if the statement glshademodel(gl_smooth); had been executed. Alternately, the statement glshademodel(gl_flat); could be used to cause the entire primitive to be assigned a color based on the second point (or a selected vertex, for polygons) to be drawn. See the shading demo program. 34 17

Fill-Area Attributes Polygons are typically filled with a solid color, or a pattern, or not filled at all. Filling can be accomplished in two ways on raster systems (once the pixel positions of the boundary have been identified): Determine the regions of scan lines that cross over the polygon and fill these regions, line by line. Start by filling any interior point, and then work outward, pixel-by-pixel, until the primitive boundary is reached. 35 Fill Patterns An arbitrary pattern can usually be used to fill a polygon, and this pattern can be specified in several ways: A rectangular array of color information that specifies the colors for the interior of the polygon A bit array that specifies which bits in the interior of the polygon are to be filled with color. In this case, the bit array is applied to a starting position in the polygon (cropping the fill at the edges), and is then replicated horizontally and vertically until the entire interior has been filled. When a rectangular pattern is used, this procedure is called tiling. Some systems may provide predefined patterns, called hatch fill patterns. 36 18

Color-Blended Fill Regions Obviously other schemes can be used to determine how the interior of a primitive is filled. Soft-fill, or tint-fill, can be used to alter fill colors with another, perhaps using a linear combination of the current background color and the new fill color. For example, the new color P for a pixel in the polygon could be computed as P = tf + (1 t)b where the transparency factor t is 0 t 1, F is the foreground color, and B is the background color. This equation holds for each of the primary RGB colors. 37 Selecting t The transparency factor can be computed using one of the RGB color components as t = (P k B k ) / (F k B k ) where F k B k. Similar procedures can be used for merging with several background colors, such as might be found in a checkerboard pattern. In this case, the linear combination might use t 0, t 1, and (1 t 0 t 1 ) as the weights. 38 19

Scan-Line Polygon Fill Algorithm Recall that a raster system might fill a polygon by sweeping across those scan lines intersecting the polygon and filling those pixels that are interior to the polygon. An important step in this algorithm is determining whether a pixel is inside the polygon, or outside, on the scan line that crosses the polygon. 39 Simple Fill Pixel Selection On the scan line (blue), the pixels shown in red would receive the fill color. It s easy to see that the pixels between scan line intersections with the polygon edges are selected. 40 20

The Basic Algorithm The basic algorithm, then, is straightforward: Repeat for each scan line that intersects the polygon: Set x to Set count (an integer) to 0 While x is less than Scan right to the next intersection with a polygon edge, filling pixels with the fill color (or pattern) if count is odd. Update x to indicate the current position (which will be if we re done). Increment count 41 Complications y y Look at scan line y should count be incremented by 1 or 2 when it intersects with the vertex? Using your answer to the previous question, process scan line y and assess the results. 42 21

Results y y If our algorithm blindly assumes that the count should be incremented by 2 (or not incremented, so the parity isn t altered), then scan line y is processed correctly. But the vertex on scan line y should have been counted only once! 43 A Solution One solution to this problem is obtained by noting that the vertex on scan line y has both edges that meet at the vertex on the same side of the scan line. For scan line y, the two edges that meet are on different sides of the scan line. Clearly the vertex count should be incremented by 2 (or not incremented at all) only if both edges at a vertex are on the same side of the line. 44 22

First Implementation Approach A (somewhat obvious) implementation of this approach would require that we trace around the vertices in the polygon in clockwise (or counterclockwise) order and keep track of the relative change in the y value of the vertices. If three consecutive endpoint y values of vertices monotonically increase (or decrease), then the middle (second, shared) vertex through which our scan line passes should be counted as a single edge crossing for the algorithm. Otherwise, the shared vertex is a local minimum or maximum y value for the two edges, and a scan line that crosses at the shared vertex should be treated as crossing twice. 45 Second Implementation Approach Another approach to implementing the solution is to shorten one of the edges in a pair of edges with monotonically increasing (or decreasing) y values. If we re clever, we can decrease the length of the lower edge (upper edge if the values are decreasing) just enough so that it appears as if its upper vertex isn t the same as the lower vertex of the upper edge. Now the scan line will intersect only one line when it passes through the original vertex, but the edges differ by only one pixel so they still appear as if they were joined. 46 23

Exploiting Coherence The algorithm just presented requires a lot of computation. However it can be simplified somewhat by exploiting the fact that the slope of an edge of a polygon doesn t change from one scan line to the next. This property can be used to determine the x coordinate of the next scan line s intersection point with the current edge. 47 Coherence Example y k+1 y k x k+1 = x k + 1/m x k x k+1 y k+1 = y k + 1 48 24

Additional Efficiency Considerations The algorithm can be made more efficient by recording the non-horizontal edge information in a table, sorted in scan line number (that is, y) order. For each y position where a polygon edge begins or ends, we make an entry in the table. Since multiple edges may have vertices with the same y values, there may be multiple entries in the table for each y value. Thus it s appropriate to use a linked list for each y value. 49 Implementation As each edge in the polygon is visited, the minimum y value in that edge identifies the scan line number, and thus the linked list into which an entry will be made. The entry includes the y value of the other end of the edge, the x value of the vertex, the inverse slope of the edge (for coherence calculations), and a pointer to the next edge with a lower vertex on the same scan line. (See fig. 6-50 in the text.) 50 25

51 Filling Convex Polygons and Triangles Filling a convex polygon is simplified by the fact that there is no more than one interior span of pixels to be filled for each scan line. For each scan line, we will either encounter a single intersection with a vertex (which is filled with the appropriate color), or we will encounter two intersections with edges (or vertices), filling the pixels between the first and second intersection with the appropriate color or pattern. Triangle fills are even simpler, since there are only three edges to consider. 52 26

Filling Areas with Curved Boundaries Curved boundaries complicate fill algorithms somewhat, but not excessively. For simple curves (circles, ellipses), fill algorithms similar to those for convex polygons can be used, with endpoints determined by formula. The midpoint method used to draw the curve can be used to identify the endpoints of each scan line. Curved sections (e.g. those bounded by two different curves, or a curve and a line) use a combination of the procedures already mentioned. Complex curves take the most work, but since boundaries for such curves are often approximated with polygons, the techniques are easy to implement. 53 Filling Areas with Irregular Boundaries Two algorithms are appropriate to fill areas that have irregular boundaries (e.g. those drawn by hand with a drawing program). The boundary-fill algorithm works outward from a point in the interior, filling until it reaches the boundary of the area, each pixel of which has the same boundary color. The flood-fill algorithm works similarly, but only fills pixels that have the same background color. 54 27

Boundary-Fill Techniques The boundary-fill algorithm can be used if a region has a connected boundary, each pixel of which has the same color. Starting with a single interior pixel, adjoining pixels can be selected using the 4-connected or 8-connected approaches to identify neighboring pixels. The 4-connected approach uses pixels that are right, left, above, and below the current pixel. The 8-connected approach additionally uses pixels that are diagonally connected; this approach is appropriate for filling more complex figures. (See fig. 6-54 in the text.) 55 56 28

Boundary Fill Good and Bad In the left picture, the region with the black border was boundaryfilled with red. Since the border is continuous, the fill was successful. In the right picture, the red border isn t connected, so the boundary fill (with yellow) filled the entire picture. 57 A Problem A recursive algorithm may not fill regions correctly if some of the interior pixels already have the fill color. This is because the algorithm doesn t perform a recursive invocation if it encounters a pixel that has the appropriate interior color or the boundary color. To avoid this problem, a separate (recursive) pass over all the pixels could be made to change any pixels with the desired new fill color to something else (except the boundary color, of course). 58 29

Boundary-Fill Algorithm (Vers. 1) The boundary-fill algorithm is easily understood as a recursive algorithm: boundary_fill_4 (int x, int y, int fillcolor, int boundarycolor) { int interiorcolor; getpixel(x,y,&interiorcolor); if (interiorcolor!= fillcolor && interiorcolor!= boundarycolor) { setpixel(x,y,fillcolor); boundary_fill_4(x+1,y,fillcolor,boundarycolor); boundary_fill_4(x-1,y,fillcolor,boundarycolor); boundary_fill_4(x,y+1,fillcolor,boundarycolor); boundary_fill_4(x,y-1,fillcolor,boundarycolor); } } 59 Improving Boundary-Fill Although it s easy to see that the first version of the boundary-fill algorithm will identify and fill all pixels (assuming the 4-connected approach suffices), it s clear that it wastes a great deal of time examining pixels that have already been processed. A smarter approach is to process pixels on each scan line, keeping track of the location of the leftmost pixel for each neighboring (above or below) scan line (there will be less stacking ). 60 30

Boundary-Fill Algorithm (Vers. 2) 1. Fill left and right (to the boundary) from the starting pixel position S, pushing on a stack the leftmost pixel positions in the upper and lower scan lines that begin regions with the background color. 2. Pop the stack to get a new starting pixel position P (if the stack is empty, we re done). Starting at P, work right to a pixel with the boundary color, filling as we go, and stacking the leftmost upper (if P is above S, or lower, if P is below S) pixel positions that begin regions with the background color. 3. Repeat from step 2. 61 62 31

The Flood-Fill Algorithm flood_fill_4 (int x, int y, int fillcolor, int interiorcolor) { int color; getpixel(x,y,&color); if (color == interiorcolor) { setpixel(x,y,fillcolor); flood_fill_4(x+1,y,fillcolor,interiorcolor); flood_fill_4(x-1,y,fillcolor, interiorcolor); flood_fill_4(x,y+1,fillcolor, interiorcolor); flood_fill_4(x,y-1,fillcolor, interiorcolor); } } 63 OpenGL Fill-Pattern Function OpenGL normally fills a polygon with the current color. This action can be modified by enabling GL_POLYGON_STIPPLE, in which case the polygon fill pattern, specified as a 32-bit by 32-bit mask (starting with the bottom row) to the glpolygonstipple function, will be used to fill the polygon. Although the fill pattern is only 32 by 32, it is replicated (tiled) to fill the entire polygon. 64 32

Example Filled Polygon 65 Texture and Interpolation Patterns OpenGL can also fill polygons with patterns that appear as textures (e.g. wood, metal, brick). Colors can be specified differently for each vertex of a polygon, and OpenGL will provide a linear interpolation of the colors when the polygon is filled. As usual, glshademodel(gl_smooth) must be used (which is the default) for this interpolation to take place. Using GL_FLAT will cause the last color specified to be used. 66 33

Linear Color Interpolation Example 67 34