Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2 Computer Graphics and Visualization SSE, Mukka

Similar presentations


Presentation on theme: "Chapter 2 Computer Graphics and Visualization SSE, Mukka"— Presentation transcript:

1 Chapter 2 Computer Graphics and Visualization SSE, Mukka
GRAPHICS PROGRAMMING Chapter 2 Computer Graphics and Visualization SSE, Mukka

2 Highlights of the chapter
Programming oriented approach is used. Minimal application programmer's interface (API) is used which allow to program many interesting two- and three-dimensional problems, and to familiarize with the basic graphics concepts. 2-D graphics is regarded as a special case of 3-D graphics. Hence the 2-D code will execute without modification on a 3-D system. A simple but informative problem called: The Sierpinski gasket” is used. 2-D programs that do not require user interaction can be written with knowledge presented here. The chapter is concluded with an example of a 3-D application. in slides on Chapter 2 Adapted from Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009

3 The Sierpinski Gasket Problem
The Sierpinski gasket is an object that can be defined recursively and randomly in the limit, however, it has properties that are not at all random Consider the three vertices in the plane. Assume that their locations, as specified in some convenient coordinate system, are (Xl, Y1), (X2, Y2), and (X3, Y3). The construction proceeds as follows:

4 Construction of Gasket
1. Pick an initial point at random inside the triangle. 2. Select one of the three vertices at random. 3. Find the point half way between the initial point and the randomly selected vertex. 4. Display this new point by putting some sort of marker, such as a small circle, at its location. . 5. Replace the initial point with this new point. 6. Return to step 2. Thus, each time a point that is generated, it is displayed on the output device. In the figure p0 is the initial point, and Pl and P2 are the first two points generated by the algorithm.

5 A possible form for our graphics program
main( ) { initialize_the_system(); for (some_number_of_points) pt = generate_a_point(); display_the_point(pt); } cleanup();

6 Programming 2-D applications
To produce the image of a 3-D object on 2-D pad of pen-plotter model, the positions of 2-D points corresponding to points on 3-D object are to be specified. These two-dimensional points are the projections of points in three-dimensional space. The mathematical process of determining projections is an application of trigonometry. An API allows users to work directly in the domain of their problems, and to use computers to carry out the details of the projection process automatically, without the users having any trigonometric calculations within the application program

7 Contd… For 2-D applications, such as the Sierpinski gasket, discussion is started with a three-dimensional world. Mathematically, a 2-D plane or a simple 2-D curved surface is viewed as a subspace of a three-dimensional space. Hence, statements-both practical and abstract -about the bigger 3-D world will hold for the simpler 2-D one. We can represent a point in the plane z=0 as p = (x, y, 0) in 3-D, or as p = (x, y) in 2-D subspace corresponding to the plane.

8 Contd… In OpenGL, internal representation for both 2-D and 3-D points is same. Hence a 3-D point is represented by a triplet: regardless of in what coordinate system p is represented. Vertex ( rather than point): A vertex is a location in space (in Computer Graphics a 2-D, 3-D, 4-D spaces are used). Vertices are used to define the atomic geometric objects that are recognized by graphics system. The simplest geometric object is a point in space, which is specified by a single vertex. Two vertices define a line segment. Three vertices can determine either a triangle or a circle. Four vertices determine a quadrilateral, and so on.

9 Multiple Forms of functions
OpenGL has multiple forms for many functions. The variety of forms allows the user to select the one best suited for the problem. General for of the vertex function is glVertex* where the * can be interpreted as either two or three characters of the form nt or ntv, where -n signifies the number of dimensions (2, 3, or 4); -t denotes the data type, such as integer (i), float (f), or double (d); -v, if present, indicates the variables are specified through a pointer to an array, rather than through an argument list. Regardless of which form a user chooses, the underlying representation is the same.

10 Basic OpenGL types GLfloat and GLint, are used rather than the C types, such as float and int. These types are defined in the header files and usually in the obvious way-for example, #define GLfloat float However, use of the OpenGL types allows additional flexibility for implementations for example, suppose the floats are to be changed to doubles without altering existing application programs.

11 Contd.. Returning to the vertex function, if the user wants to work in 2-D with integers, then the form glVertex2i(GLint xi, GLint yi) is appropriate glVertex3f(GLfloat x, GLfloat y, GLfloat z) specifies a position in 3-D space using floating-point numbers. If an array is used to store the information for a 3-D vertex, GLfloat vertex[3] then glVertex3fv(vertex) can be used.

12 Geometric primitives Different numbers of vertices are required depending on the object. Any number of vertices can be grouped using the functions glBegin and glEnd. The argument of glBegin specifies the geometric type that the vertices define. Hence, a line segment can be specified by glBegin(GL_LINES); glVertex2f(xl,yl); glVertex2f(x2,y2); glEnd();

13 Contd… Same data can be used to define a pair of points, by using the form, glBegin(GL_POINTS); glVertex2f(xl,yl); glVertex2f(x2,y2); glEnd();

14 Heart of Sierpinski gasket program
Suppose that all points are to be generated within a 500 x 500 square whose lower left-hand corner is at (0,0) - a convenient, but easily altered, choice. How to represent geometric data in program? A two-element array for 2-D points is used: typedef GLfloat point2[2]; A function called display, is created to generate 5000 points each time it is called. Assume that an array of triangle vertices triangle[3] is defined in display as an array of point2.

15 display function void display(void) { point2 triangle[3] = {{0.0, 0.0}, {250.0, 500.0}, {500.0, 0.0}}; /* an arbitrary triangle */ static point2 p = {75.0, 50.0}; /* or set to any desired initial point */ int j, k; int rand(); /* standard random-number generator*/ for(k=0;k<5000;k++) j = rand()%3; /* pick a random vertex from 0,1, 2 */

16 Contd… p[0] = (p[0] + triangle[j][0])/2; /* compute new point */ p[1] = (p[1] + triangle[j][1])/2; glBegin(GL_POINTS); /* display new point */ glVertex2fv(p) ; glEnd(); } glFlush();

17 The function rand is a standard random-number generator that produces a new random integer each time that it is called. Modulus operator is used to reduce these random integers to the three integers 0, 1, and 2. The call to glFlush ensures that points are rendered to the screen as soon as possible. If it is left, the program works correctly, but in a busy or networked environment there may be noticeable delay. A complete program is not yet written.

18 Figure below shows the expected output:

19 Issues leftwith 1. Color of drawing.
2. Position of the image on the screen. 3. Size of the image. 4. Window (area on the screen) for the image. 5. How much of the infinite pad will appear on the screen? 6. How long will the image remain on the screen? The basic code answering these questions and to control the placement and appearance of renderings will not change substantially across programs.

20 Coordinate Systems Graphics systems allow users to work in any desired coordinate system. The advent of device independent graphics freed application programmers from worrying about the details of input and output devices. World coordinate system or the Problem coordinate system: It is the user's coordinate system. Device Coordinates: Units on the display. E.g. For raster devices, such as most CRT displays, the term raster coordinates or screen coordinates is used. Raster coordinates are always expressed in some integer type, because the center of any pixel in the frame buffer must be located on a fixed grid, or, equivalently, because pixels are inherently discrete and they can be addressed using integers.

21 At some point, the values in world coordinates must be mapped into device coordinates, as shown in figure The graphics system, rather than the user, is responsible for this task, and the mapping is performed automatically as part of the rendering process. To define this mapping, the user needs to specify only a few parameters-such as the area of the world to be seen and the size of the display.

22 The OpenGL API Till now we saw – Need to know how
Heart of Sierpinski gasket program Need to know how To gain control over the appearance of the object on display To control the flow of the program To interact with the window system To specify primitives to be displayed

23 Why only OpenGL API OpenGL’s structure is similar to that of most modern APIs Java3D and DirectX Any effort in learning OpenGL will carry over to other software systems OpenGL is easy to learn, it is nevertheless powerful It supports simple 2-D and 3-D programs as well as advanced rendering techniques Our primary goal is to study Computer Graphics We are using OpenGL API to attain that goal So will not mention all OpenGL functions

24 Graphics Functions Graphics package model can be viewed as a black box
Black box - a term that engineers use to denote a system whose properties are described by only its inputs and outputs; nothing is known about its internal workings. Hence graphics system can be viewed as a box whose inputs are function calls from a user program (say measurements from input devices, such as the mouse and keyboard and possibly other input, such as messages from the operating system); outputs are primarily the graphics sent to the output devices.

25 Graphics functions contd…
An API is defined through the functions in its library. A good API may contain hundreds of functions It is helpful to divide the functions into six groups by their functionality: Primitive functions Attribute functions Viewing functions Transformation functions Input functions Control functions Query functions

26 Contd… The primitive functions define the low-level objects or atomic entities that the system can display. Depending on the API, the primitives can include points, line segments, polygons, pixels, text, and various types of curves and surfaces. If primitives are what of an API- the objects that can be displayed, then attributes are the how. That is, the attributes govern the way that a primitive appears on the display. Attribute functions perform operations ranging from choosing the color, to picking a pattern with which to fill the inside of a polygon, to selecting a type face for the titles on a graph.

27 Contd… Synthetic camera must be described to create an image.
Its position and orientation in our world must be defined, and equivalent of a lens must also be selected. This process not only will fix the view, but also clip out objects that are too close or too far away. The viewing functions specify various views. One of the characteristics of a good API is that it provides the user with a set of transformation functions that carry out transformations of objects, such as rotation, translation, and scaling

28 Contd… For interactive applications, the API provides a set of input functions to deal with diverse forms of input that characterize modern graphics systems say functions to deal with devices such as keyboards, mice, and data tablets In any real application, the complexities of working in a multiprocessing multi-window environment (usually a network environment) may need to be handled. The control functions communicate with the window system, to initialize the programs, and to deal with any errors that take place during the execution of programs.

29 Query functions Query functions: They provide useful information of API that can be useful in an application. E.g. Camera parameters or values in the frame buffer. To write device-independent programs, the implementation of the API need to take care of differences between devices, such as how many colors are supported or the size of the display. There are applications where some properties of the particular implementation need to be known. E.g. If the programmer knows in advance the display device at work supports only two colors rather than millions of colors, things the programmer chooses might be different. A good API provides this information through a set of query functions.

30 The OpenGL Interface GL (Graphics Library): OpenGL function names begin with the letters gl and are stored in a library usually referred to as GL. There are a few related libraries: Graphics utility library (GLU): This library uses only GL functions, but contains code for common objects, such as spheres, that users prefer not to have to write repeatedly. This library is available in all OpenGL implementations. GL Utility Toolkit (GLUT): It addresses the problems of interfacing with the window system. It provides the minimum functionality that should be expected in any modern windowing system. System specific library is required for establishing interaction But instead of using a diff library every time, we use readily available GLUT – provides min functionality expected in any modern windowing system

31 Contd… Figure below shows the organization of the libraries for an X Window system environment. Note that various other libraries are called from the OpenGL libraries, but that the application program does not need to refer to these libraries directly. A similar organization holds for other environments, such as Microsoft Windows.

32 Contd.. OpenGL makes heavy use of macros to increase code readability and to avoid the use of magic numbers. Thus, strings such as GL_FILL and GL_POINTS are defined in header ( . h) files. In most implementations, one of the include lines #include <GL/glut.h> or #include <glut.h> is sufficient to read in glut.h, gl.h, and glu. h.

33 Primitives and attributes
OpenGL basic library has a small set of primitives an additional library, GLU, contains a richer set of objects derived from the basic library. OpenGL supports 2 classes of primitives: Geometric primitives Image or raster primitive Geometric primitives include points, line segments, polygons, curves and surfaces These primitives pass through a geometric pipeline, where they are subjected to a series of geometric operations Raster primitives, such as array of pixels, lack geometric properties and hence cannot be manipulated in same way

34 Primitives and attributes
The basic OpenGL primitives are specified via points in space or vertices. Thus, the programmer defines objects with sequences of the form glBegin(type); glVertex*( . . .); glVertex*(...); glEnd(); The value of type specifies how OpenGL interprets the vertices to define geometric objects

35 Contd… Other code and OpenGL function calls can occur between glBegin and glEnd. E.g. Attributes can be changed or calculations can be performed for the next Vertex between glBegin and glEnd, or between two invocations of glVertex A major conceptual difference between the basic geometric types is whether or not they have interiors. Aside from the point type, all the other basic types will be defined either in terms of vertices or by finite pieces of lines, called line segments Of course, a single line segment is itself specified by a pair of vertices

36 Contd… The line segment is of such importance that it can be considered a basic graphical entity. The use of line segments can be: To define approximations to curves. To connect data values for a graph. For the edges of closed objects, such as polygons, that have interiors.

37 Line segments (GL_LINES) The line-segment type causes successive pairs of vertices to be interpreted as the endpoints of individual segments. Because the interpretation is done on a pair wise basis, successive segments usually are disconnected. Polylines (GL_LINE_STRIP) It is used if successive vertices (and line segments) are to be connected. Many curves can be approximated via a suitable polyline. GL_LINE_LOOP: If the polyline need to be closed the final vertex is located in the same place as the first, or GL_LINE_LOOP can be used which will draw a line segment from the final vertex to the first, thus creating a closed path.

38 Polygon Basics Line segments and polylines can model the edges of objects, but closed objects also may have interiors as shown in figure Polygon refers to an object that has a border that can be described by a line loop, but has an interior. Polygons play a special role in computer graphics because they can be displayed rapidly and they can be used to approximate arbitrary or curved surfaces. The performance of graphics systems is measured by the number of polygons per second that can be displayed.

39 Ways of displaying polygons
Only its edges be displayed. Its interior be filled with a solid color, or a pattern Either display or not display the edges. Outer edges of a polygon can be defined easily by an ordered list of vertices. But if the interior is not well defined, then the polygon may be rendered incorrectly.

40 Three properties of a polygon
Three properties will ensure that a polygon will be displayed correctly: It must be simple, convex, and flat. Simple: A 2-D polygon in which no pair of edges cross each other. They will have well-defined interiors. Although the locations of the vertices determine whether or not a polygon is simple, the cost of testing is sufficiently high that most graphics systems require that the application program do any necessary testing. Non-simple: Graphics system must handle by some means if a non-simple polygon is to be displayed and to define an interior for a non-simple polygon.

41 Convex An object is convex if all points on the line segment between any two points inside the object, or on its boundary, are inside the object regardless of the type of the object and its dimension (whether 2-D or 3-D). Convex objects include triangles, tetrahedra, rectangles, circles, spheres, and parallelepipeds. There are various tests for convexity. However, like simplicity testing, convexity testing is expensive and usually is left to the application program.

42 Convex objects

43 Flat In 3-D, polygons present a few more difficulties, because, unlike all 2-D objects, they are not necessarily flat i.e., all vertices that define polygon need not lie in the same plane. One property that most graphics systems exploit, and that can be used, is that any three vertices that are not collinear determine both a triangle and the plane in which that triangle lies. Hence, the use of only triangles is safe in rendering such objects correctly.

44 Polygon types in OpenGL
For objects with interiors, we can specify following types Polygons (GL_POLYGON): Successive vertices define line segments, and a line segment connects the final vertex to the first. The interior is filled according to the state of the relevant attributes. Note that a mathematical polygon has an inside and an outside that are separated by the edge. The edge itself has no width. Consequently, most graphics systems allow to fill the polygon with a color or pattern or to draw lines around the edges, but not to do both. In OpenGL, glPolygonMode function can be used to select edges instead of fill (the default). However, to draw a filled polygon and to display its edges, it must be drawn twice, once in each mode, or a polygon and a line loop with the same vertices must be drawn.

45 Triangles and Quadrilaterals (GL_TRIANGLES, GL_QUADS)
These objects are special cases of polygons. Successive groups of three and four vertices are interpreted as triangles and quadrilaterals, respectively. Using these types may lead to a rendering more efficient than that obtained with polygons.

46 Strips and Fans (GLTRIANGLE_STRIP, GL_QUAD_STRIP, GL_TRIANGLE_FAN)
These objects are based on groups of triangles or quadrilaterals that share vertices and edges.   In the triangle_strip, for example, each additional vertex is combined with the previous two vertices to define a new triangle.

47 Strips and Fans (GLTRIANGLE_STRIP, GL_QUAD_STRIP, GL_TRIANGLE_FAN)
For the quad_strip, two new vertices are combined with the previous two vertices to define a new quadrilateral. A triangle fan is based on one fixed point. The next two points determine the first triangle, and subsequent triangles are formed from one new point, the previous point, and the first (fixed) point.

48

49 Approximating a Sphere
Many curved surfaces can be approximated using fans and strips. E.g. To approximate to a sphere, a set of polygons defined by lines of longitude and latitude as shown can be used. Either quad strips or triangle strips can be used for the purpose. Consider a unit sphere. It can be described by the following three equations: x(θ, Ø)= sinθ cosØ , y(θ, Ø)= cosθ cosØ, z(θ, Ø) = sinØ.

50 Contd… Circles of constant longitude can be obtained by fixing θ and varying Ø. Likewise, circles of constant latitude can be obtained by fixing Ø and varying θ. Quadrilaterals can be defined by generating points at fixed increments of θ. Degrees must be converted to radians for the standard trigonometric functions. The code for the quadrilaterals corresponding to increments of 20 degrees in θ and to 20 degrees in Ø is, given below:

51 code for(phi=-80.0; phi<=80.0; phi+=20.0) { phir=c*phi; phir20=c*(phi+20); glBegin(GL_QUAD_STRIP); for (theta=-180.0; theta<=180.0; theta+=20.0) thetar=c*theta; x=sin(thetar)*cos(phir); y=cos(thetar)*cos(phir); z=sin(phir); glVertex3d(x,y,z); x=sin(thetar)*cos(phir20); y=cos(thetar)*cos(phir20); z=sin(phir20); glVertex3d(xty,z); } glEnd( );

52 Contd… But strips can not be used at the poles, because all lines of longitude converge there. Instead two triangle fans one at each pole can be used, as follows: glBegin(GL_TRIANGLE_FAN); glVertex3d(0.0, 0.0, 1.0); c=M_PI/180.0; c80=c*80.0; z=sin(c80); for(thet=-180.0;theta<=180.0;theta += 20.0) { thetar=c*theta; x=sin(thetar)*cos(c80); y=cos(thetar)*cos(c80); glVertex3d(x,y,z); } glEnd( ); 

53 Contd.. glBegin(GL_TRIANGLE_FAN); glVertex3d(0.0, 0.0, -1.0);
z = -sin(c80); for(theta=-180.0; theta<=180.0; theta += 20.0) { thetar=c*theta; x=sin(thetar)*cos(c80); y=cos(thetar)*cos(c80); glVertex3d(x,y,z); } glEnd( );

54 Text In computer graphics text may need to be displayed in a multitude of fashions by controlling type styles, sizes, colors, and other parameters. (Note that in non graphical applications, a simple set of characters, are displayed in the same manner). Graphics applications must provide a choice of fonts. Fonts are families of type faces of a particular style, such as Times, Computer Modern, or Helvetica. Two types Stroke text Raster text

55 Stroke Text It is constructed as are other graphic primitives.
Vertices are used to define line segments or curves that outline each character. The characters defined by closed boundaries can be filled. Advantage It can be defined to have all the detail of any other object It can be manipulated by standard transformations, and viewed like any other graphical primitive. It can be manipulated by different transformations (can be made bigger or rotated). It retains its detail and appearance even after manipulations. Consequently, a character is needed to be defined only once, transformations can be used to generate it at the desired size and orientation.

56 Raster text It is simple and fast.
Characters are defined as rectangles of bits called bit blocks. Each block defines a single character by the pattern of 0 and 1 bits in the block. A raster character can be placed in the frame buffer rapidly by a bit-block-transfer (bitblt) operation, which moves the block of bits using a single instruction OpenGL allows the application program to use instructions that allow direct manipulation of the contents of the frame buffer. Size of raster characters can be increased only by replicating or duplicating pixels, a process that gives larger characters a blocky appearance.

57 Limitations of Raster Text
Other transformations of raster characters, such as rotation, may not make sense because the transformation may move the bits defining the character to locations that do not correspond to the location of pixels in the frame buffer. Raster characters often are stored in read-only memory (ROM) in the hardware and hence, a particular font might be of limited portability.

58 Text in OpenGL Because stroke and bitmap characters can be created from other primitives, OpenGL does not have a text primitive. However, GLUT provides a few bitmap and stroke character sets that are defined in software and are portable. E.g. A bitmap character of 8 x 13 pixels can be produced by glutBitmapCharacter(GLUT_BITMAP_8_BY_13, c) where c is the number of the ASCII character to be placed on the display. The character is placed at the present raster position on the display, a location that is part of the graphics state, is measured in pixels, and can be altered by the various forms of the function glRasterPos*

59 Curved Objects Two approaches to create richer set of objects (means not the primitives) like curved surfaces: Primitives can be approximated to curves and surfaces. E.g. A regular polygon of n sides can be approximated to draw a circle. A regular polyhedron can be approximate to a sphere. Tessellation: Generally, a mesh of convex polygons can be approximated to a curved surface either at the rendering stage or within the user program. Curved objects are defined mathematically and then graphics functions can be built to implement those objects. Objects such as quadric surfaces and parametric polynomial curves and surfaces are well understood mathematically, and they can be specified through sets of vertices. (Chapter 10) E.g. A sphere is defined by its center and a point on its surface. A cubic polynomial curve can be defined by four points.

60 Curved objects in OpenGL
Most graphics systems give aspects of both approaches. In OpenGL, utility library (GLU) can be used for a collection of approximations to common curved surfaces, and functions can be written to define other own objects. Advanced features of OpenGL can also be to work with parametric polynomial curves and surfaces.

61 Attributes It is any property that determines how a geometric primitive is to be rendered. Each geometric type has a set of attributes. Type of the primitive differs from its attribute. E.g. A red solid line and a green dashed line are the same geometric type, but each is displayed differently. Attributes may be associated with, or bound to, primitives at various points in the modeling and rendering pipeline.

62 Immediate-mode graphics
In this, primitives are not stored in the system, but rather are passed through the system for possible display as soon as they are defined. The present values of attributes are part of the state of the graphics system. When a primitive is defined, the present attributes for that type are used, and it is displayed immediately. There is no memory of the primitive in the system. Only the primitive's image appears on the display; once erased from the display, it is lost.

63 Color Color in computer graphics is based the three-color theory which says: “If two colors produce the same tristimulus values, then they are visually indistinguishable.” Two colors that match visually are known as metameric pairs; they have the same tristimulus values.

64 additive color model It is more appropriate for CRT displays with the primaries red, green, and blue. This model considers a color, as being formed from three primary colors that are mixed to form the desired color. All colors can not be matched in this way. But with a particular set of primaries, say standard red, green, and blue, combined, a color close to the desired one can be obtained.

65 Contd.. The matching process can be represented abstractly as follows.
Matching Color i.e., C = T1R + T2G + T3B, were R, G, and B represent the three primaries Red, Green and Blue respectively. T1, T2, T3 are the strengths, or intensities, of the three primaries, called the tristimulus values. Thus relative to the particular set of primaries, the target color can be characterized by the triplet (T1, T2, T3). Thus a continuous function is reduced to three numbers. Hence for a visual match, only a color's tristimulus values are to be matched.   Color Gamut: The range of colors that can be produced on a given system with a given set of primaries.

66 Color Cube In additive color model, a color is viewed as a point in a color solid The solid is drawn using a coordinate system corresponding to the three primaries. The distance along a coordinate axis represents the amount of the corresponding primary in the color. The maximum value of each primary is normalized to 1 and hence any color can be represented with this set of primaries as a point in a unit cube. The vertices of the cube correspond to black (no primaries on); red, green, and blue (one primary fully on); the pairs of primaries, cyan (green and blue fully on), magenta (red and blue fully on), and yellow (red and green fully on); and white (all primaries fully on). The principal diagonal of the cube connects the origin (black) with white. All colors along this line have equal tristimulus values and appear as shades of gray. With additive color, primaries add light to an initially black display, yielding the desired color.

67 Subtractive color model
It suits for processes such as commercial printing and painting. The primaries are usually the complementary colors: cyan, magenta, and yellow (CMY). RGB additive system has a dual with a CMY subtractive system.

68 Color handling in a graphics system from the programmer's perspective - i.e. , through the API.
There are two different approaches. RGB Color Model – In a three-primary-color, additive-color RGB system, there are conceptually separate frame buffers for red, green, and blue images. Each pixel has separate red, green, and blue components that correspond to locations in memory.

69 Contd.. In a typical system, there might be a 1280 x 1024 array of pixels, and each pixel might consist of 24 bits (3 bytes): 1 byte for each of red, green, and blue. Such a frame buffer would have over 3 megabytes (MB) of memory that would have to be redisplayed at video rates. Programmers specify any color that can be stored in the frame buffer. With 24-bits/pixel, 224 (16 M ) colors are possible.. Programmers specify color components as numbers (using the color cube) between 0.0 and 1.0, where 1.0 denotes the maximum value of the corresponding primary, and 0.0 denotes a zero value of that primary.

70 Graphic Function: for color
In OpenGL, to draw in red, the following function call is used: glColor3f(1.0, 0.0, 0.0); The execution of this function will set the present drawing color to red. Because the color is part of the state, draw in red is continued until the color is changed. The "3f" is used in a manner similar to the glVertex function: It conveys that, a three-color (RGB) model is used, and that the values of the components are given as floats in C. If an integer or byte type to specify a color value, the maximum value of the chosen type corresponds to the primary fully on, and the minimum value corresponds to the primary fully off.

71 Advantages and Disadvantages:
RGB Model is used in lighting and shading. It is a more difficult model to support in hardware, due to higher memory requirements, but modern systems support it more easily now that memory is cheaper. Many systems have frame buffers that are limited in depth. Consider a frame buffer having a spatial resolution of l280 x 1024, but each pixel is only 8 bits deep. The 8 bits can be divided into smaller groups of bits to assign to red, green, and blue. Although this technique is adequate in a few applications, it usually does not give enough flexibility in color assignment, and breaking apart individual bytes into small groups of bits can affect performance.

72 Four-color (RGBA) system
 The fourth color (A) uses what is called the alpha channel, but is stored in the frame buffer, as are the RGB values; it can be set with four-dimensional versions of the color functions. Various uses of the alpha channel, such as for creating fog effects or for combining images. alpha value is just used in the initialization of an OpenGL program. The alpha value will be treated by OpenGL as an opacity or transparency value. Transparency and opacity are complements of each other. An opaque object passes no light through it; a transparent object passes all light. An object can range from fully transparent to fully opaque.

73 To clear an area of the screen-a drawing window-in which output is displayed:
It is done as first step in any program Whenever a new frame is to be drawn. The function call glC1earCo1or(1.0, 1.0, 1.0, 1.0); defines a four-color clearing color that is white, because the first three components are set to 1.0, and is opaque, because the alpha component is 1.0. Then the function glC1ear is used to make the window on the screen solid and white.

74 Indexed Color Model Analogy:
It is analogous to an artist who paints in oils. The oil painter can produce an almost infinite number of colors by mixing together a limited number of pigments from tubes. It can be said that the painter has a potentially large color palette. At anyone time, however, perhaps due to a limited number of brushes, the painter uses only a few colors from a large palette. Similarly, if a limited number of colors from a large selection (palette) can be chosen, the graphics system must be able to produce good-quality images most of the time.

75 Indexed Color Model Description:
This model is used when pixel-depth is limited. Colors can be selected by interpreting the limited-depth pixels as indices, rather than as color values. These indices correspond to lines or entries in a table. Suppose that the frame buffer has k bits per pixel. Each pixel value or index is an integer between 0 and 2k - 1. Suppose that the colors can be displayed with an accuracy of m bits; that is, it is possible to chose from 2m reds, 2m greens, and 2m blues. Hence, any of 23m colors can be produced on the display, but the frame buffer can specify only 2k of them. The specification is handled through a user-defined color-lookup table of size 2k x 3m.

76 Contd…. The user program fills the 2k entries (rows) of the table with the desired colors, using m bits for each of red, green, and blue. After filling the look-up table, user can then specify a color by its index, which points to the appropriate entry in the color-lookup table. For k =m = 8, a common configuration, user can choose 256 out of 16 M colors. The 256 entries in the table constitute the user's color palette.

77 Graphics Functions In color-index mode, the present color is selected by a function such as glIndex1(element); that selects a particular color out of the table. Setting and changing the entries in the color-lookup table involves interacting with the window system.  One difficulty is that, if the window system and underlying hardware support only a limited number of colors, the window system may have only a single color table that must be used for all its windows, or it might have to juggle multiple tables, one for each window on the screen. GLUT allows to set the entries in a color table for each window through the function glutSetColor(int color, GLfloat red, GLfloat blue, GLfloat green)

78 Advantages and Disadvantages
This model is used when pixel-depth is limited. It requires less memory for the frame buffer and fewer other hardware components. However, the cost issue is less important now, and color-index mode presents a few problems. For a standard 8-bit (256-color) frame buffer, a limited set of colors exist to represent a single image adequately. However, when working with dynamic images that must be shaded, more colors are usually needed.

79 Setting of Color Attributes using RGB color model
3 attributes of the colors: Clear color, which is set to white by the function call glClearColor(l.0, 1.0, 1.0, 1.0); Rendering color for the points by setting the color state variable to red through the function call glColor3f(1.0, 0.0, 0.0); Size of rendered points: For 2 pixels wide, following call is used. glPointSize(2.0);

80 Viewing Viewing decisions are to be specified in the program.
A fundamental concept that emerges from the synthetic-camera model is that, the specification of the objects in the scene is completely independent of the specification of the camera. Once both the scene and the camera have been specified, the computer system forms an image by carrying out a sequence of operations in its viewing pipeline. The application program needs to worry about only specification of the parameters for the objects and the camera. There are default viewing conditions (like lens adjustment in camera) in computer image formation.

81 Orthographic view Simplest and OpenGL’s default view is
orthographic projection Mathematically, the orthographic projection is what we would get if the camera in our synthetic-camera model had an infinitely long telephoto lens and we could then place the camera infinitely far from our objects We can approximate this effect by leaving the image plane fixed and moving the camera far from this plane In the limit all projectors become parallel and the center of projection is replaced by a direction of projection

82 How to get camera infinite distance away?
Instead we start with projectors that are parallel to z-axis and the projection plane at z=0 Not only are the projectors perpendicular to the projection plane, but also we can slide the projection plane along the z-axis without changing where the projectors intersect the plane.

83 Orthographic viewing Special orthographic camera that resides in the projection plane ( assuming ) A reference point in the projection plane from which we can make measurements of a view volume and a direction of projection In OpenGL, reference point start off at the origin and the camera points in the –ve z-direction

84 Contd… Orthographic projection takes a point (x,y,z) and projects it into the point (x,y,0) In 2-D viewing, with all vertices in plane z=0, a point and its projection both are same In OpenGL, an orthographic projection with a right parallelpiped viewing volume is specified via the following void glOrtho(Gldouble left, Gldouble right, Gldouble bottom, Gldouble top, Gldouble near, GLdouble far) Sees only those objects in the volume specified by the viewing volume It can also include objects that are behind the camera!

85 Contd.. If viewing volume is not specified, OpenGL uses its default, a 2 x 2 x 2 cube, with the origin in the center. In terms of 2-D plane, the bottom-left corner is at(-1.0, -1.0), and the upper-right corner is at (1.0, 1.0). 2-D graphics view is a special case of 3-D graphics. Hence the viewing rectangle is in the plane z = 0 within 3-D viewing volume:

86 2-D viewing 2-D viewing: is based on taking a rectangular area of 2-D world and transferring its contents to the display. The area of the world of which the image is to be taken is known as the viewing rectangle or clipping rectangle. Objects inside the rectangle are in the image; objects outside are clipped out and are not displayed. Objects that straddle the edges of the rectangle are partially visible in the image. If using a 3-D volume seems strange in a two-dimensional application, the function void gluOrtho2D(GLdoub1e left, GLdouble right, GLdouble bottom, GLdouble top) in the utility library may make the program more consistent with its 2-D structure. This function is equivalent to glOrtho with near and far set to -1.0 and 1.0, respectively.

87 Matrix modes Pipeline graphics systems have an architecture that depends on multiplying together, or concatenating, a number of transformation matrices to achieve the desired image of a primitive. Like most other OpenGL variables, the values of these matrices are part of the state of the system and remain in effect until changed. The two most important matrices are Model-view and Projection matrices. At any time, the state includes values for both of these matrices, which start off set to identity matrices. The usual sequence is to modify the initial identity matrix, by applying a sequence of transformations.

88 Matrix mode Setting the matrix mode selects the matrix to which the operations apply. It is a variable that is set to one type of matrix and is also part of the state. The default matrix mode is to have operations apply to the model-view matrix. So to alter the projection matrix, modes must be switched. The following sequence is common for setting a 2-D viewing rectangle: glMatrixMode(GL_PROJECTION); glLoadIdentity( ); gluOrtho2D(0.0, , 0.0, ); glMatrixMode(GL_MODELVIEW); This sequence defines a 500 x 500 viewing rectangle with the lower-left corner of the rectangle at the origin of the 2-D system. It then switches the matrix mode back to model-view mode. In complex programs, it is always better to return to a given matrix mode, to avoid possible confusion over the current mode. E.g. In this case mode returned to model-view mode.

89 Control Functions The OpenGL Utility Toolkit (GLUT) is a library of functions that provides a simple interface between the systems. Details specific to the underlying windowing or operating system are inside the implementation, rather than being part of its API. The application programs written using GLUT run under multiple window systems.

90 Interaction with the Window System
The term window is used in a number of different ways in the graphics and workstation literature. Window or screen window denotes a rectangular area of our display that, by default, is the screen of a raster CRT. It has a height and width. It displays the contents of the frame buffer. So, positions in the window are measured in window or screen coordinates, where the units are pixels. In a modern environment, many windows can be displayed on the CRT screen. Each can have a different purpose, ranging from editing a file to monitoring the system. The term window system refers to the multi-window environment provided by systems such as the X Window system and Microsoft Windows.

91 Contd… The window in which the graphics output appears is one of the windows managed by the window system. Hence, to the window system, the graphics window is a particular type of window-one in which graphics can be displayed or rendered. References to positions in this window are relative to one corner of the window. While deciding which corner is the origin, much care must be taken. Usually, the lower-left corner is the origin, and has window coordinates (0, 0). However, virtually all raster systems display their screens from top to bottom, left to right. From this perspective, the top-left corner should be the origin. OpenGL commands assume that the origin is bottom-left. But information returned from the windowing system, such as the mouse position, often has the origin at the top left and thus requires conversion of the position from one coordinate system to the other. Although screen may have a resolution of, say, 1280 x 1024 pixels, the window that used can have any size, up to the full screen size. Thus, the frame buffer must have a resolution equal to the screen size. Conceptually, use of a window of say, 300 x 400 pixels is corresponding to a 300 x 400 frame buffer, even though it uses only a part of the real frame buffer.

92 Graphics GLUT functions
1. glutInit(int *argcp, char **argv) It initiates an interaction between the windowing system and OpenGL. It is used before opening a window in the program. The two arguments allow the user to pass command-line arguments, as in the standard C main function, and are usually the same as in main. 2. glutCreateWindow(char *tit1e) It opens an OpenGL window. title string provides title at the top to the window displayed.

93 Contd… The window thus created has a default size, a position on the screen, and characteristics such as use of RGB color. But GLUT functions are also available to specify these parameters before to the window creation. E.g. The code glutInitDisp1ayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutIn1tW1ndowSize(480, 640); glutInitWindowPosition(0, 0); specifies a 480 x 640 window in the top-left corner of the display. RGB is specified rather than indexed (GLUT_INDEX)color; a depth buffer for hidden-surface removal; and double rather than single (GLUT_SINGLE) buffering. The defaults, which are needed now, are RGB color, no hidden-surface removal, and single buffering. Thus, these options need not explicitly specified. But specifying them makes the code clearer. Note that parameters are logically OR-ed together in the argument to glutInitDisplayMode.


Download ppt "Chapter 2 Computer Graphics and Visualization SSE, Mukka"

Similar presentations


Ads by Google