Introduction to Computer Graphics EEL 5771-001 PPT3: Attributes of Graphics Primitives Karthick...

100
Introduction to Computer Graphics EEL 5771-001 PPT3: Attributes of Graphics Primitives Karthick Rajendran U3116-6141

Transcript of Introduction to Computer Graphics EEL 5771-001 PPT3: Attributes of Graphics Primitives Karthick...

Slide 1

Introduction to Computer GraphicsEEL 5771-001PPT3: Attributes of Graphics PrimitivesKarthick Rajendran U3116-6141

IntroductionColor and Grey ScaleLine AttributesPen and Brush OptionsLine StyleCurve AttributesFill-Area AttributesScan-Line Polygon FillScan-Line Fill MethodsWire-Frame MethodsCharacter AttributesAnti-aliasing

2

2Attributes of Graphics Primitives : IntroductionAny parameter that affects the way one of the Graphics Primitives to be displayed is referred to as an Attribute Parameter.Some attribute parameters are size, color, style, font, orientation.How to incorporate these attribute options into graphics package?Extend the parameter list associated with each output primitive function to include appropriate attributes.Maintain a system list of current attribute values and use separate functions to set attributes.

3

Introduction (Ctd.)Few Attributes for various Primitives are shown below

4

Color and Grey ScaleA basic attribute for all primitives is color. Various color and intensity-level options can be made available to a user, depending on the capabilities and design objectives of a particular system.Extend the parameter list associated with each output primitive function to include appropriate attributes.Maintain a system list of current attribute values and use separate functions to set attributes.

There are a number of color models that are in common use. RGB CYM HSB.We generally use RGB colors in OpenGLColors are represented by colors codes which are positive integers.Color information is stored in frame buffer or in separate table and use pixel values as index to the color table.

5Color : RGB ColorsRGB colors are specified by giving the amount of red green and blue needed to create the color.

RGB is an additive color model - like when you mix colored lights. No color is black. Putting all the colors together makes white. This model matches what happens in a CRT where each pixel emits some amount of red, green and blue light.

Color values can be given as integers from 0 to 255 or floating point numbers from 0 to 1.RGBA colors have a fourth value that represents transparency

6

Color : Color TablesA color table is useful when your frame buffer doesnt have enough bits to support all the colors you want to use.If you need 24 bit color values and only have 8 bits per pixel, you make a table with 256 entries each of which is a 24-bit color. The frame buffer holds an index into the table for each color which only needs 8 bits.By changing between different color tables you can use more than 28 colors in your graphics.Color-Index mode is used in OpenGL to create color tables.The figure illustrates a color look uptable.7

Color : Color Tables8 Bit Color : 8-bit colorgraphics is a method of storing image information in a computer's memory or in an image file, such that eachpixelis represented by one 8-bitbyte. The maximum number of colors that can be displayed at any one time is 256.

8

Color : Color Tables24 Bit Color(True Color): True colorsupports 24-bit for threeRGBcolors. It provides a method of representing and storing graphical-image information (especially in computer processing) in anRGB color spacesuch that a very large number of colors, shades, and hues can be displayed in an image, such as in high-quality photographic images or complex graphics. Usually, true color is defined to mean 256 shades of red, green, and blue, for a total of 224or 16,777,216 color variations. The human eye can discriminate up to ten million colors."True color" can also refer to an RGB display-mode that does not need a color look-up table.

9

Color : Color look-upTable Acolor look-up table(CLUT) is a mechanism used to transform a range of input colors into another range of colors. It can be a hardware device built into an imaging system or a software function built into animage processingapplication. The hardware color look-up table will convert the logical color (pseudo-color) numbers stored in each pixelofvideo memoryinto physical colors, normally represented asRGBtriplets, that can be displayed on a computer monitor.

10

Color : Color look-upTableA common example would be a palette of 256 colors; that is, the number of entries is 256, and thus each entry is addressed by an8-bitpixel value. The 8 bits is known as color depth,bit depthorbits per pixel(bpp). The 256 color palette is shown below:

11

Gray Scale LevelA greyscaleis an image in which the value of eachpixelis a singlesample, that is, it carries only intensity information. Images of this sort, also known asblack-and-white, are composed exclusively of shades ofgray, varying from black at the weakest intensity to white at the strongest. When an RGB color setting specifies an equal amount of red, green, and blue, the result is some shade of gray. Values close to 0 for the color components produce dark gray, and higher values near 1.0 produce light gray.

12

13Gray Scale Level.Apply for monitor that have no color.Shades of grey (white->light grey->dark grey->black).Color code mapped onto grayscale codes.2 bits can give 4 level of grayscale.8 bits per pixel will allow 256 combination.Dividing the actual code with 256 will give range of 0 and 1

Ex:Color code in color display is 118

To map to nearest grayscale then118/256 = 0.45

light gray

Line AttributesThe attributes for a line are color, width and style.For wide lines we have to worry about what the ends and intersections look like. Can draw lines in OpenGL using either GL_LINES in glBegin or as the fill mode for a polygon. In addition, we have GL_LINE_STRIP and GL_LINE_LOOP. The current color is used.TypesSolidDotted very short dash with spacing equal to or greater than dash itself

Dashed displayed by generating an inter-dash spacing.

Pixel count for the span and inters-pan length is specifiedby the mask . Ex. 111100011110001111

14Line AttributesDisplaying Thick Lines.These thick(wide)lines can be displayed in several ways.

Draw multiple 1-pixel wide lines next to each other to get the desired width.

15

Line AttributesReplace each pixel in a line by either a horizontal or vertical span of the appropriate number of pixels. Use the slope to decide which direction the span goes.

Figure out the vertices of a filled rectangle of the right height and width with the line centered inside it.

16

Line AttributesUse a brush pattern.

Ensuring proper ending of thick lines: Thick lines are drawn with (a) butt caps, (b) round caps, and (c) projecting square caps.

17

Line AttributesFor Lines that intersect: With square end caps, the intersection between two wide lines can look messy if we dont do something to correct it.Most graphics packages allow you to specify a miter join, a round join or a bevel join.

18

Line StylesSometimes we want something other than solid lines dashed or dotted lines for example.One common approach is to specify a pixel mask that indicates how many contiguous pixels are on to make the dashes and how many are off to make the spaces between them. For example, 11110000 would have the same length for the dashes and the space between them. The mask 11111000 would have longer dashes than spaces. hick(wide)lines can be displayed in several ways.Note that when counting pixels like this, the dashes will look different lengths for different orientations.

Could also draw a dashed line as a sequence of line segments.

19

20Pen and Brush OptionsPen and Brush. The selected pen or brush determine the way a line will be drawn.. Pens and brushes have size, shape, color and pattern attribute.. Pixel mask is applied in both of them

21Pen and Brush OptionsPen and Brush : Common Examples

Curved AttributesCurve attributes are basically the same as for lines except different approaches lead to slightly different appearances. Thicker curves can be produced by:1. Plotting additional pixel2. Filling the space between two concentric circles.3. Using thicker pen or brushUsing horizontal and vertical pixel spans depending on the slope:

(Fig) Circular Arc of width 4 plotted withpixel spans.

22

Curved AttributesFilling the space between two concentric circles.

Use a brush (square in this case):

23

Curved AttributesExamples of Common Pen shapes

24

Fill-Area AttributesThree ways to fill an area :1. with nothing 2. with a solid color 3. with a pattern - either apply the pattern to the region or blend it with the background color.

25

Fill-Area AttributesThree basic fill styles are:1. hollow with color border.. interior color is same with background

2627Fill-Area Attributes2. filled with a solid color .. color up to and including the border

3. pattern .. control by other table Fill-Area AttributesArea fill with logic operators.

28

Introduction to PolygonsDifferent types of PolygonsSimple ConvexSimple ConcaveNon-simple : self-intersectingWith holes

ConvexConcaveSelf-intersectingIntroduction to PolygonsConvex A region S is convex iff for any x1 and x2 in S, the straight line segment connecting x1 and x2 is also contained in S. The convex hull of an object S is the smallest H such that SRendering: Scan-line area fill The algorithm (Hearn, Baker, Carithers, Computer Graphics) Scan-line algorithms Purpose: given a set of (2D) vertex coordinates for a polygon, fill the area surrounded by the polygon Polygons can be filled with a uniform colour or texture

Scan Line Algorithm - OutlineEssential in rendering, i.e. conversion of geometric entities into image pixels Used, for example, in Display of polygons Hidden surface removal Texture mapping For each scan line (each y-coordinate) Compute x coordinates of the intersections of the current scan line with all edges Sort these edge intersections by increasing x value Group the edge intersections by pairs (vertex intersections require special processing) Fill in the pixels on the scan line between pairs of values

Scan Line AlgorithmBuild edge table Initialise scan-line list 2 Find first non-empty bucket (ymin) in the edge table 3 While the current ymin not greater than topmost y coordinate of the polygon 3.1 merge the edge table for the current ymin with scan-line list, sort on increasing xmin 3.2 fill pixels between pairs of rounded xmin-s 3.3 Remove from the scan-line list the edges whose ymax = current scanline 3.4 increment xmin by the increment (1/m) for remaining edges in the scan list 3.5 re-sort scan line list on increasing xmin 3.6 increment current scanline ymin to give next scanline

Scan Line Polygon Fill AlgorithmsA standard output primitive in general graphics package is a solid color or patterned polygon area:There are two basic approaches to filling on raster systems.Determine overlap Intervals for scan lines that cross that area.Start from a given interior point and paint outward from this point until we encounter the boundaryThe first approach is mostly used in general graphics packages, however second approach is used in applications having complex boundaries and interactive painting systems

Xk+1,yk+1Xk , ykScan Line yk +1Scan Line yk Scan Line Polygon Fill AlgorithmInterior pixels along a scan line passing through a polygon area For each scan line crossing a polygon are then sorted from left to right, and the corresponding frame buffer positions between each intersection pair are set to the specified color. These intersection points are then sorted from left to right , and the corresponding frame buffer positions between each intersection pair are set to specified color 10 14 18 24Scan Line Polygon Fill AlgorithmIn the given example ( previous slide) , four pixel intersections define stretches from x=10 to x=14 and x=18 to x=24

Some scan-Line intersections at polygon vertices require special handling:A scan Line passing through a vertex intersects two polygon edges at that position, adding two points to the list of intersections for the scan LineIn the given example , scan Line y intersects five polygon edges and the scan Line y intersects 4 edges although it also passes through a vertexy correctly identifies internal pixel spans ,but need some extra processing

Scan line Polygon Fill AlgorithmOne way to resolve this is also to shorten some polygon edges to split those vertices that should be counted as one intersection

When the end point y coordinates of the two edges are increasing , the y value of the upper endpoint for the current edge is decreased by 1

When the endpoint y values are monotonically decreasing, we decrease the y coordinate of the upper endpoint of the edge following the current edgeScan Line Polygon Fill AlgorithmAdjusting endpoint values for a polygon, as we process edges in order around the polygon perimeter. The edge currently being processed is indicated as a solid like. In (a), the y coordinate of the upper endpoint of the current edge id decreased by 1. In (b), the y coordinate of the upper end point of the next edge is decreased by 1(a)(b)

Otherwise, the shared vertex represents a local extremum (min. or max.) on the polygon boundary, and the two edge intersections with the scan line passing through that vertex can be added to the intersection listFigureIntersection points along the scan lines that intersect polygon vertices. Scan line y generates an odd number of intersections, but scan line y generates an even number of intersections that can be paired to identify correctly the interior pixel spans. The scan conversion algorithm works as followsIntersect each scanline with all edgesSort intersections in xCalculate parity of intersections to determine in/outFill the in pixelsSpecial cases to be handled:Horizontal edges should be excludedFor vertices lying on scanlines, count twice for a change in slope.Shorten edge by one scanline for no change in slopeCoherence between scanlines tells us thatEdges that intersect scanline y are likely to intersect y + 1X changes predictably from scanline y to y + 1

We have 2 data structures: Edge Table and Active Edge Table Traverse Edges to construct an Edge TableEliminate horizontal edgesAdd edge to linked-list for the scan line corresponding to the lower vertex.Store the following:y_upper: last scanline to considerx_lower: starting x coordinate for edge1/m: for incrementing x; computeConstruct Active Edge Table during scan conversion. AEL is a linked list of active edges on the current scanline, y. Each active edge line has the following informationy_upper: last scanline to considerx_lower: edges intersection with current y1/m: x incrementThe active edges are kept sorted by x

Scan Line Fill

Scan Line Fill

Scan Line Fill

Scan Line Fill Running the Algorithm

Scan Line Fill Running the Algorithm

Scan Line Fill Running the Algorithm

Scan line Fill Method Using a Stack Sample program//The scanline fill algorithm using our own stack routines, faster

void floodFillScanlineStack(int x, int y, int newColor, int oldColor){ if(oldColor == newColor) return; emptyStack(); int y1; bool spanLeft, spanRight; if(!push(x, y)) return;

while(pop(x, y)) {

Scan line Fill Method Using a Stack Sample Programy1 = y; while(y1 >= 0 && screenBuffer[x][y1] == oldColor) y1--; y1++; spanLeft = spanRight = 0; while(y1 < h && screenBuffer[x][y1] == oldColor ) { screenBuffer[x][y1] = newColor; if(!spanLeft && x > 0 && screenBuffer[x - 1][y1] == oldColor) { if(!push(x - 1, y1)) return; spanLeft = 1; } else if(spanLeft && x > 0 && screenBuffer[x - 1][y1] != oldColor) { spanLeft = 0; }Scan line Fill Method Using a Stack Sample Programif(!spanRight && x < w - 1 && screenBuffer[x + 1][y1] == oldColor) { if(!push(x + 1, y1)) return; spanRight = 1; } else if(spanRight && x < w - 1 && screenBuffer[x + 1][y1] != oldColor) { spanRight = 0; } y1++; } }}Wire Frame MethodsAwire-frame modelis a visual presentation of a three-dimensional (3D) or physical object used in3D computer graphics. It is created by specifying each edge of the physical object where two mathematically continuous smooth surfaces meet, or by connecting an object's constituentverticesusing straight lines or curves. The object is projected onto a display screen by drawing lines at the location of each edge. The term wire frame comes from designers using metal wire to represent the three-dimensional shape of solid objects.Sample rendering of a wire-framecube,icosahedron, and approximatesphere

Wire Frame MethodsThe following sets of images show a wireframe version, a wireframe version with hidden line removal, and a solid polygonal representation of the same object.

Character AttributesCurve attributes are basically the same as for lines except different approaches lead to slightly different appearances. Font Style underline, boldface, italics, outline, shadow plain bold italic underline double underline outline shadowColor Character spacingHeight to width ratio can sometimes be manipulated The orientation of the text is specified by defining the up vector

52

Character AttributesText can go horizontal or vertically and forward or backward Alignment of the text as a whole relative to some reference point (left, center, right, top, bottom)

53

Anti AliasingWhat is Aliasing and Anti-Aliasing ?

Aliasing occurs when a continuous signal is discretized.This distortion of information due to low-frequency sampling (undersampling) is called aliasing. We can improve the appearance of displayed raster lines by applying antialiasing methods that compensate for the undersampling process.Anti-Aliasing Anti-aliasing is the term for methods that reduce the unwanted aliasing artifacts. 54AliasingAliasing explained through a set of images.The appearance of a texture-mapped triangle depends on the mapping between a triangle outline and a textured map.

55

AliasingIf the mapping is not one-to-one, significant artifacts can occur.Even when it is nearly one-to-one, artifacts can appear

56

Jaggies or Stair casingJaggies an informal name for artifacts from poorly representing continuous geometry by a discrete 2D grid of pixels.Jaggies also called Stair case effects are a manifestation of sampling error and loss of information (aliasing of high frequency components by low frequency ones)

57

Examples of AliasingIf the mapping is not one-to-one, significant artifacts can occur.Even when it is nearly one-to-one, artifacts can appear

58

Examples of Aliasing

59

Examples of Aliasing

60

Examples of Aliasing

61

Examples of Aliasing

62

Causes of AliasingAliasing is caused by under sampling. If we dont sample a continuous signal at a high enough rate, we wont have a good representation of the signal

63

When Does Spatial Aliasing Occur?During image synthesis: when sampling a continuous (geometric) model to create a raster image, Example: scan converting a line or polygon. Sampling: converting a continuous signal to a discrete signal.

During image processing and image synthesis: when resampling a picture, as in image warping or texture mapping. Resampling: sampling a discrete signal at a different sampling rate. Example: zooming a picture from n x by ny pixels to sn x by sny pixels s>1: called upsampling or interpolation can lead to blocky appearance if point sampling is used. s 0 ? F1(x,y) > 0 ? F2(x,y) > 0 ? a sphere can be specified by its radius R and its center point (xc,yc,zc) (x-xc)2 + (y-yc)2 + (z-zc)2 = R2

75Anti AliasingGraphical objects (e.g., lines, polygons) Graphical objects are generally specified mathematically Input signal may have infinite frequency components e.g., from abrupt transitions from black to white

76

Anti AliasingGraphical objects may have infinite frequency components e.g., across edges of a polygon.

77

Anti AliasingHow do you band-limit a piece of geometry? Render the image at a higher sampling rate and then filter the rendered image to reduce aliasing artifacts - Supersampling

Apply a filtering to the geometry as we render - Analytic / Coverage-based filtering

Use a different mathematical representation so shapes dont have a sharp transition from outside to inside - Distance-based antialiasing

78Anti Aliasing

79

Anti Aliasing

80

Anti Aliasing

81

Anti Aliasing

82

Anti Aliasing

83

Anti Aliasing

84

Anti Aliasing

85

Anti Aliasing

86

Anti Aliasing

87

Anti Aliasing

88

Area Samplingshade pixels according to the area covered by thickened linethis is unweighted area sampling

a rough approximation formulated by dividing each pixel into a finer grid of pixelsUnweighted Area SamplingConsider a line as having thickness (all good drawing programs do this)

Consider pixels as little squares

Fill pixels according to the proportion of their square covered by the line

Other variations weigh the contribution according to where in the square the primitive falls1/81/8.914.914.9141/81/81/41/41/41/400000000000000Alpha-based Anti-AliasingRather than setting the intensity according to coverage, set the The pixel gets the line color, but with = 8.0) lineWidth = 0.5;glLineWidth(lineWidth);

break;case 'x': eyex=12.0; eyey=0.0; eyez=0.0; break;case 'y': eyex=0.05; eyey=12.0; eyez=0.0; break;case 'z': eyex=0.0; eyey=0.0; eyez=12.0; break;case 27:case 'e':case 'E': exit(0);break;default: break;}glutPostRedisplay();}

Antialiasing Exampleint main(int argc, char** argv){glutInit(&argc, argv);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(500, 500);glutCreateWindow( argv[0]);init();glutReshapeFunc(reshape);glutKeyboardFunc(keyboard);glutDisplayFunc(display);glutSpecialFunc( specialkeys );glutMainLoop();return 0;}108Introduction - Text book and image : https://root.cern.ch/basic-graphics-primitiveshttp://cs.boisestate.edu/~tcole/cs341/fall04/vg/6ch4.pdf

Color & Grey scalehttps://en.wikipedia.org/wiki/8-bit_colorhttp://dmp.dijonyellow.com/digital_photography/Color.htmhttps://en.wikipedia.org/wiki/Grayscalehttp://www.codeproject.com/Questions/327689/how-to-convert-coloured-image-to-grayscale-in-C-orhttp://www.songho.ca/dsp/luminance/luminance.htmlhttps://root.cern.ch/basic-graphics-primitiveshttp://up.edu.ps/ocw/repositories/upinar_data%2022008/upinar_data%2022008/580/slides/http://www.slideshare.net/1lakshmi1/attributes-of-outputprimitives-44298566

References 109line attributeshttp://cs.boisestate.edu/~tcole/cs341/fall04/vg/6ch4.pdfhttp://www.cs.utexas.edu/~fussell/courses/cs324e2003/hear50265_ch04.pdfhttps://www.google.com/search?q=pen+and+brushes+pixel+pattern&es_sm=93&biw=1366&bih=667&source=lnms&tbm=isch&sa=X&ved=0CAYQ_AUoAWoVChMIhNHqifL9xwIV07IeCh21dAXy#tbm=isch&q=pen+and+brushes+pattern+example+graphics

http://www.cs.bham.ac.uk/~vvk201/Teach/Graphics/14_ScanLineFill.pdfThe animations copied from Prof. Harriet Fellslecture slides, College of Computer and InformationScience, Northeastern Universityhttp://lodev.org/cgtutor/floodfill.html#Scanline_Floodfill_Algorithm_With_Stackhttps://en.wikipedia.org/wiki/Wire-frame_modelhttp://www.cs.uic.edu/~jbell/CourseNotes/ComputerGraphics/VisibleSurfaces.htmlReferences 110https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB4QFjAAahUKEwil4bn-w_7HAhWDXR4KHY4yBC0&url=http%3A%2F%2Fpeople.sju.edu%2F~swei%2Fcsc341%2FSlides%2Fpolygonfill.ppt&usg=AFQjCNFbFN5cH5rsPOFicB8vpCPWal5iGA&sig2=EkSxQoJxAddWVQjoVsC08A

http://www.cs.tufts.edu/~sarasu/courses/comp175-2009fa/pdf/comp175-08-antialiasing.pdfhttp://classes.cec.wustl.edu/~cse452/lectures/lect03_image_processing.pdfhttps://sisu.ut.ee/sites/default/files/imageprocessing/files/aliasing.pdfReferences