Presentation is loading. Please wait.

Presentation is loading. Please wait.

UNIT 3 : GRAPHICS PROGRAMMING USING OPENGL

Similar presentations


Presentation on theme: "UNIT 3 : GRAPHICS PROGRAMMING USING OPENGL"— Presentation transcript:

1 UNIT 3 : GRAPHICS PROGRAMMING USING OPENGL
Anjuman College of Engineering and Technology Department of Computer Science & Engineering Fifth Semester Subject: COMPUTER GRAPHICS UNIT 3 : GRAPHICS PROGRAMMING USING OPENGL Prepared By Prof. Sadia Patka Assistant Professor

2 OpenGL (Open Graphics Library) – What & Why?
OpenGL is a software interface for graphics hardware; OpenGL's main purpose is to render two- and three dimensional objects into a frame buffer. These objects are described as sequences of vertices (which define geometric objects) or pixels (which define images). OpenGL performs several processing steps on this data to convert it to pixels to form the final desired image in the frame buffer. OpenGL is a cross language, multi-platform application programming interface (API) for rendering 2D & 3D vector graphics. It is used to interact with a graphics processing unit (GPU) to achieve hardware accelerated rendering. OpenGL is a software interface that allows the programmer to create 2D and 3D graphics images. OpenGL is both a standard API and the implementation of that API. You can call the functions that comprise OpenGL from a program you write and expect to see the same results no matter where your program is running. OpenGL is independent of the hardware, operating, and windowing systems in use. The fact that it is windowing-system independent, makes it portable. OpenGL program must interface with the windowing system of the platform where the graphics are to be displayed. Therefore, a number of windowing toolkits have been developed for use with OpenGL.

3 Contd.. OpenGL functions in a client/server environment. That is, the application program producing the graphics may run on a machine other than the one on which the graphics are displayed. The server part of OpenGL, which runs on the workstation where the graphics are displayed, can access whatever physical graphics device or frame buffer is available on that machine. OpenGL's rendering commands however are "primitive". You can tell the program to draw points, lines, and polygons, and you have to build more complex entities upon these. With OpenGL any commands that you execute are executed immediately. That is, when you tell the program to draw something, it does it right away. You also have the option of putting commands into display lists. A display list is a not editable list of OpenGL commands stored for later execution. You can execute the same display list more than once. For example, you can use display lists to redraw the graphics whenever the user resizes the window. You can use a display list to draw the same shape more than once if it repeats as an element of the picture. OpenGL is hardware-independent. Many different vendors have written implementations that run on different hardware. These implementations are all written to the same OpenGL standard and are required to pass strict conformance tests. Vendors with licenses include SGI, AT&T, DEC, Evans & Sutherland, Hitachi, IBM, Intel, Intergraph, Kendall Square Research, Kubota Pacific, Microsoft, NEC, and RasterOps. The RS/6000 version comes with X and Motif extensions. However X is not required to run OpenGL since OpenGL also runs with other windowing systems.

4 Features in OpenGL 3D Transformations – it allows transformation operations such as rotations, scaling, translation, perspective, etc. Color models – it accepts values like R, G, B, alpha. Lighting – it includes different methods of shading like Flat shading, Gouraud shading, Phong shading Rendering – it allows texture mapping Modeling – non-uniform rational B-spline (NURB) is a mathematical model used for generating curves and surfaces. Other features includes – atmospheric fog, alpha blending, motion blur

5 Basic OpenGL Operation/ OpenGL Pipeline/ Architecture
Display List Polynomial Evaluator Per Vertex Operations & Primitive Assembly Rasterization Per Fragment Operations Frame Buffer Texture Memory CPU Pixel Figure 1: OpenGL Pipeline

6 Contd.. The figure 1 shown above gives an abstract, high-level block diagram of how OpenGL processes data. In the diagram, commands enter from the left and proceed through what can be thought of as a processing pipeline. Some commands specify geometric objects to be drawn, and others control how the objects are handled during the various processing stages. All data, whether it describes geometry or pixels, can be saved in a display list for current or later use. If the data is geometric then it is passed to polynomial evaluator. All geometric primitives are described by vertices. The evaluator stage of processing provides an efficient means for approximating curve and surface geometry by evaluating polynomial commands of input values. Now the vertex data is passed to per vertex operations and primitive assembly. The per-vertex operations stage converts the vertices into primitives. If advanced features are enabled, this stage is even busier. If texturing is used, texture coordinates may be generated and transformed here. If lighting is enabled, the lighting calculations are performed. A major part of primitive assembly is clipping. It eliminates the portions of geometry which fall outside defined by a plane. If the data is pixel then it takes a different route. The pixel data from display list is passed to the pixel operation stage. Pixels from an array in system memory are first unpacked from one of a variety of formats into the proper number of components. Next the data is scaled, biased, and processed by a pixel map. The results are clamped and then either written into texture memory or sent to the rasterization step. If pixel data is read from the frame buffer, pixel-transfer operations (scale, bias, mapping, and clamping) are performed. Then these results are packed into an appropriate format and returned to an array in system memory.

7 Contd.. If the result of the pixel operation stage is written to texture memory it will make the images more realistic. Now both types of data go through the same final steps i.e. a rasterization and per-fragment operation. Rasterization is the conversion of both geometric and pixel data into fragments. Each fragment square corresponds to a pixel in the frame buffer. Line and polygon stipples, line width, point size, shading model, and coverage calculations to support antialiasing are taken into consideration as vertices are connected into lines or the interior pixels are calculated for a filled polygon. Color and depth values are assigned for each fragment square. Before values are actually stored into the frame buffer, these values are passed to fragment operations stage where a series of operations are performed that may alter or even throw out fragments. All these operations can be enabled or disabled. The first operation that takes place here is texturing, then fog calculations may be applied, then, blending, dithering, logical operation, and masking by a bitmask may be performed. Finally, the thoroughly processed fragment is drawn into the appropriate buffer, where it has finally advanced to be a pixel and achieved its final resting place.

8 Abstractions in OpenGL/ OpenGL-Related Libraries/OpenGL APIs
As mentioned, OpenGL is window and operating system independent. To integrate it into various window systems, additional libraries are used to modify a native window into an OpenGL capable window. Every window system has its own unique library and functions to do this. Some examples are: GLX for the X Windows system, common on Unix platforms AGL for the Apple Macintosh WGL for Microsoft Windows Generally, applications which require more user interface support will use a library designed to support those types of features (i.e. buttons, menu and scroll bars, etc.) such as Motif or the Win32 API. Prototype applications, or one which don’t require all the bells and whistles of a full GUI, may choose to use GLUT instead because of its simplified programming model and window system independence.

9 Contd.. Libraries are the operating system dependent implementation of OpenGL on the system you’re using. Each operating system has its own set of libraries. For Unix systems, the OpenGL library is commonly named libGL.so and for Microsoft Windows, it’s named opengl32.lib. Header files describe all of the function calls, their parameters and defined constant values to the compiler. OpenGL has header files for GL (the core library), GLU (the utility library), and GLUT (freeware windowing toolkit). There are three types of header files used in a OpenGL program #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> The below figure 2 illustrates the relationships of the various libraries and window system components.

10 Contd.. GLUT GLU GL X, Win32, Mac O/S software and/or hardware
GLX, AGL or WGL X, Win32, Mac O/S software and/or hardware OpenGL Motif widget or similar Figure 2 : OpenGL APIs

11 Contd.. 1) GL - Graphic Library It is lowest level in abstraction.
It stands for Graphic Library. It provides Primitives which consist points, line, polygons It provides Shading and Coloring of images It can provides Translation, rotation, scaling in 2D & 3D It can provides Viewing, Clipping, Texturing It also provides Hidden surface removal algorithm. It consists of all basic library functions which can be used for drawing an image.

12 Contd.. 2) GLU - The OpenGL Utility Library
OpenGL also includes a utility library, GLU, to simplify common tasks such as: rendering quadric surfaces (i.e. spheres, cones, cylinders, etc.), working with NURBS and curves, and concave polygon tessellation. The OpenGL Utility Library (GLU) contains several routines that use lower-level OpenGL commands to perform such tasks as setting up matrices for specific viewing orientations and projections, performing polygon tessellation, and rendering surfaces. This library is provided as part of every OpenGL implementation.

13 Contd.. 3) GLUT - The OpenGL Utility Toolkit
Finally to simplify programming and window system dependence, we’ll be using the freeware library, GLUT. GLUT, written by Mark Kilgard, is a public domain window system independent toolkit for making simple OpenGL applications. It simplifies the process of creating windows, working with events in the window system and handling animation. In addition, since OpenGL drawing commands are limited to those that generate simple geometric primitives (points, lines, and polygons), GLUT includes several routines that create more complicated three-dimensional objects such as a sphere, a torus, and a teapot.

14 Argument Data Types and Command Suffixes
There are three basic data types – 1) GL int, 2) GL float, 3) GL enum. To use opengl data type their abbreviations are used in suffix before command. The letters used as suffixes to specify these data types for ISO C implementations of OpenGL are shown in Table 1, along with the corresponding OpenGL type definitions.

15 Contd.. For example: glVertex2i(1, 3); glVertex2f(1.0, 3.0);
are equivalent, except that the first specifies the vertex’s coordinates as 32−bit integers, and the second specifies them as single−precision floating−point numbers.

16 OpenGL Geometric Primitives
Every OpenGL geometric primitive is specified by its vertices which are homogenous coordinates. Homogenous coordinates are of the form ( x, y, z, w ). The possible types of OpenGL primitives are: GL_POINTS - individual points GL_LINES - pairs of vertices are considered individual segments GL_LINE_STRIP - series of connected line segments GL_LINE_LOOP - a line strip that connects the first and last vertices GL_POLYGON - boundary of a simple convex polygon GL_TRIANGLES - three vertices interpreted as a triangle GL_TRIANGLE_STRIP - linked strip of triangle GL_TRIANGLE_FAN - linked fan of triangles GL_QUADS - 4 vertices representing a four sided polygon GL_QUAD_STRIP - linked strip of quads These Geometric Primitives are specified using glBegin( primType ); glEnd(); primType determines how vertices are combined.

17 Contd.. Depending on how vertices are organized, OpenGL can render any of the shown primitives. GL_QUAD_STRIP GL_POLYGON GL_TRIANGLE_STRIP GL_TRIANGLE_FAN GL_POINTS GL_LINES GL_LINE_LOOP GL_LINE_STRIP GL_TRIANGLES GL_QUADS

18 Contd.. glBegin(primtype); // type of primitive
OpenGL organizes vertices into primitives based upon which type is passed into glBegin(). Structure: glBegin(primtype); // type of primitive // vertex / vertices are defined glEnd( ); // end of definition/ specification of primitive

19 OpenGL Command Formats/ Syntax
1) glClearColor(red, green, blue, alpha); This command set/establishes what color the window will be cleared to. i.e. this command Sets background color of a window. Fourth parameter in this function is called as alpha value for the specified color. It is used as a blending parameter. Alpha is degree of transparency or opacity; May have the value 0.0 or 1.0. Alpha value of 0.0 indicates totally transparent object (you can see through it) and alpha value of 1.0 indicates a totally opaque object (you can’t see through it). It can be 0.50 for 50% of transparency or 0.75 or to any value as required.  2) glClear(GL_COLOR_BUFFER_BIT); This command actually clears the window Once the clearing color is set using glClearColor( ); command, the window is cleared to that color whenever glClear( ) is called.

20 Contd.. 3) glColor3f(red, green, blue);
This command specifies the color of the drawing objects. Where, 3f in the command defines no. of components i.e R, G, B of data type float. All objects drawn after this statement use the specified color, until the R, G, B value is set to another color.

21 Contd.. 4) glVertex2i(x,y);
This command is used to specify the vertices, where 2 is the number of components (x, y) and ‘i’ is the integer data type. As per need the command can be modified for number of components, data type, scalar values or vector values. The number of components can be 2 --- for coordinates (x, y) 3 --- for coordinates (x, y, z) 4 --- for coordinate (x, y, z, w) where the default value of z = 0 and w = 1 The data type can be ‘i’ for intger or ‘f’ for float. Command for scalar values with examples: glVertex2i(x, y); e.g. : glVertex2i(2, 3); glVertex2f(x, y); e.g. : glVertex2f(3.5, 2.5); glVertex3i(x, y, z); e.g. : glVertex3i(3, 2, 0); glVertex3f(x, y, z); e.g. : glVertex3f(3.5, 2.5, 0.0);

22 Contd.. glVertex2iv(x1, y1, x2, y2, x3, y3);
Command for vector values : glVertex2iv(x1, y1, x2, y2, x3, y3); glVertex2iv(x1, y1, x2, y2, x3, y3); e.g. : glVertex2iv(2, 3, 4, 2, 8, 6); glVertex2fv(x1, y1, x2, y2, x3, y3); e.g. : glVertex2fv(2.5, 3.5, 4.5, 2.5, 8.5, 6.5); glVertex3iv(x1, y1, z1, x2, y2, z2, x3, y3, z3); e.g. : glVertex3iv(2, 3, 0, 2, 8, 0, 6, 5, 0); glVertex3fv(x1, y1,z1, x2, y2,z2, x3, y3,z3); e.g. : glVertex3fv(2.5, 3.5, 0, 2.5, 8.5, 0, 6.5, 5.5, 0); When asterisk ‘*’ is used in this command i.e. glVertex*(values); then it accepts any combination with any data type. For example glVertex*(2, 4.5); (i.e. it has both integer as well as float values). 5) glFlush( ); This command ensures that the drawing commands are actually executed rather than stored in a buffer awaiting additional OpenGL commands. This command is used when opengl program uses single buffer only. For double buffer glutSwapBuffer( ); is used. OpenGL contexts with both front and back color buffers are double−buffered. Smooth animation is accomplished by rendering into only the back buffer (which isn’t displayed), then causing the front and back buffers to be swapped.

23 Combination of Color Codes (RGB):
Black (0.0, 0.0, 0.0) White (1.0, 1.0, 1.0) Gray (0.5, 0.5, 0.5) Red (1.0, 0.0, 0.0) Green (0.0, 1.0, 0.0) Blue (0.0, 0.0, 1.0) Yellow - (1.0, 1.0, 0.0) Cyan (0.0, 1.0, 1.0) Magenta - (1.0, 0.0, 1.0)

24 Input Modes Input devices contain a trigger which can be used to send a signal to the operating system Button on mouse Pressing or releasing a key When triggered, input devices return information (their measure) to the system Mouse returns position information Keyboard returns ASCII code.

25 Event Types Types of events in OpenGL are as follows:
Window: It can be resize, expose, iconify Mouse: click on one or more buttons of mouse is an event Motion: moving a mouse is an event Keyboard: pressing or releasing a key of keyboard is an event Idle: no event

26 Callback functions 1) glutDisplayFunc(myDisplay);
Draws/Redraw screen when window is opened or another window moved off it. 2) glutReshapeFunc(myReshape); Reports new window width and height for reshaped window. (Moving a window does not produce a reshape event. 3) glutIdleFunc(myIdle); When nothing else is going on, simply redraws display using void myIdle() 4) glutPostRedisplay(); If your program changes the contents of the window, sometimes you will have to cal glutPostRedisplay(void), which give glutMainLoop() a nudge to call the registered display callback at its next opportunity. 5) glutMouseFunc(myMouse); Handles mouse button presses. Knows mouse location and nature of button (up or down and which button).

27 Contd.. 5) glutMotionFunc(myMotionFunc);
Handles case when the mouse is moved with one or more mouse buttons pressed. 6) glutPassiveMotionFunc(myPassiveMotionFunc) Handles case where mouse enters the window with no buttons pressed. 7) glutKeyboardFunc(myKeyboardFunc); Handles key presses and releases. Knows which key was pressed and mouse location. 8) glutMainLoop() Runs forever waiting for an event. When one occurs, it is handled by the appropriate callback function.

28 GLUT Basic -- Structure of OpenGL Application
Configure and open window Initialize OpenGL state Register input callback functions render resize input: keyboard, mouse, etc. Enter event processing loop.

29 Contd.. The steps are: 1) Choose the type of window that you need for your application and initialize it. 2) Initialize any OpenGL state that you don’t need to change every frame of your program. This might include things like the background color, light positions and texture maps. 3) Register the callback functions that you’ll need. Callbacks are routines you write that GLUT calls when a certain sequence of events occurs, like the window needing to be refreshed, or the user moving the mouse. The most important callback function is the one to render your scene, which we’ll discuss in a few slides. 4) Enter the main event processing loop. This is where your application receives events, and schedules when callback functions are called.

30 Contd.. Program Structure/ Skeleton Program void main(int argc, char** argv) // program arguments { glutInit(&argc, argv); // initialize glut and gl glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Single buffer and RGB OR glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); // double buffer and RGB glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_Depth); // double buffer, RGB & depth glutInitWindowSize(int width, int height); // initial window size glutInitWindowPosition(int x, int y); // initial window position glutCreateWindow(char *string); // create window and name it init( ); // initialize OpenGl // initialize callbacks here glutDisplayFunc(myDisplay); // register the redraw function glutReshapeFunc(myReshape); // register the reshape function glutMouseFunc(myMouse); // register the mouse action function glutMotionFunc(myMotionFunc); // register the mouse motion function glutKeyboardFunc(myKeyboard); // register the keyboard action function //…similarly initializes other things as per requirement… glutMainLoop(); // enter the unending main loop }

31 Contd.. Here’s an example of the main part of a GLUT based OpenGL application. This is the model that we’ll use for most of our programs in the course. The glutInitDisplayMode() and glutCreateWindow() functions compose the window configuration step. We then call the init() routine, which contains our one-time initialization. Here we initialize any OpenGL state and other program variables that we might need to use during our program that remain constant throughout the program’s execution. Next, we register the callback routines that we’re going to use during our program. Finally, we enter the event processing loop, which interprets events and calls our respective callback routines.

32 OpenGL as a State Machine
OpenGL is a state machine. You put it into various states (or modes) that then remain in effect until you change them. As you’ve already seen, the current color is a state variable. You can set the current color to white, red, or any other color, and thereafter every object is drawn with that color until you set the current color to something else. The current color is only one of many state variables that OpenGL maintains. Others control such things as the current viewing and projection transformations; line and polygon stipple patterns, polygon drawing modes, pixel-packing conventions, positions and characteristics of lights, and material properties of the objects being drawn. Many state variables refer to modes that are enabled or disabled with the command glEnable() or glDisable(). Each state variable or mode has a default value, and at any point you can query the system for each variable’s current value. Typically, you use one of the six following commands to do this: glGetBooleanv(), glGetDoublev(), glGetFloatv(), glGetIntegerv(), glGetPointerv(), or glIsEnabled().

33 Contd.. Which of these commands you select, depends on what data type you want the answer to be given in. Some state variables have a more specific query command (such as glGetLight*(), glGetError(), or glGetPolygonStipple()). glGet*() command that returns the variable’s value, the attribute class to which it belongs, and the variable’s default value. In addition, you can save a collection of state variables on an attribute stack with glPushAttrib() or glPushClientAttrib(), temporarily modify them, and later restore the values with glPopAttrib() or glPopClientAttrib(). For temporary state changes, you should use these commands rather than any of the query commands, since they’re likely to be more efficient.

34 THANK YOU


Download ppt "UNIT 3 : GRAPHICS PROGRAMMING USING OPENGL"

Similar presentations


Ads by Google