Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit –III Graphics Programming Using OpenGL

Similar presentations


Presentation on theme: "Unit –III Graphics Programming Using OpenGL"— Presentation transcript:

1 Unit –III Graphics Programming Using OpenGL
Kaustubh Satpute Department of Computer Science and Engineering DMIETR,Wardha

2 Syllabus Graphics Programming using OPENGL: Why OpenGL,
Features in OpenGL, OpenGL operations, Abstractions in OpenGL – GL, GLU & GLUT, 3D viewing pipeline and viewing matrix specifications, a few examples and demos of OpenGL programs, Animations in OpenGL

3 Graphics Processing Unit (GPU)

4 History of OpenGL In the 1980's developing software was a challenge. Especially when you wanted to program for a wide range of graphics hardware The software developers had to write custom drivers for different Interface and devices. In the early 90's Silicon Graphics Inc.(SGI) was a leader in 3D graphics for workstations. They used an API called IRIS GL(Integrated Raster Imaging System Graphical Library) for their workstations. Competing vendors i.e. Sun Microsystems, IBM and Hewlett-Packard were also bringing 3D hardware on the market. They used another API called PHIGS(Programmers Hierarchical Graphics System ). In functionality and capability IRIS GL was superior to PHIGS New 3D hardware on the market, SGI's market share became smaller SGI made a new API based on IRIS GL called OpenGL In 1992, SGI led the creation of the OpenGL architectural review board (ARB)[Founding Companies SGI, Microsoft, IBM, DEC and Intel]

5 OpenGL? The Open Graphics Library (OpenGL) is a standard specification defining a cross-language, cross-platform Application Programming Interface (API). OpenGL provides the programmer an interface to the graphics hardware. OpenGL is a powerful, low-level rendering and modelling software library. With OpenGL it is possible to produce 2D and 3D graphics applications. OpenGL is widely used in video games, CAD, scientific applications, etc, on many different platforms. Many commercial games, such as the ID Software's Quake series, use OpenGL for their graphics engines.

6 OpenGL Basic Features:
Drawing primitives Transformations Color Lighting Display Lists Advanced features: Texture mapping Vertex Arrays Blending effects Frame buffer manipulation

7 3D Graphics Rendering Pipeline

8 OpenGL Rendering Pipeline
Display Lists All data, whether it describes geometry or pixels, can be saved in a display list for current or later use. (The alternative to retaining data in a display list is processing the data immediately - also known as immediate mode.) When a display list is executed, the retained data is sent from the display list just as if it were sent by the application in immediate mode. Evaluators All geometric primitives are eventually described by vertices. Parametric curves and surfaces may be initially described by control points and polynomial functions called basis functions. Evaluators provide a method to derive the vertices used to represent the surface from the control points. The method is a polynomial mapping, which can produce surface normal, texture coordinates, colors, and spatial coordinate values from the control points. Per-Vertex Operations For vertex data, next is the per-vertex operations stage, which converts the vertices into primitives. Some vertex data (for example, spatial coordinates) are transformed by 4 x 4 floating-point matrices. Spatial coordinates are projected from a position in the 3D world to a position on your screen. 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 using the transformed vertex, surface normal, light source position, material properties, and other lighting information to produce a color value. Primitive Assembly Clipping, a major part of primitive assembly, is the elimination of portions of geometry which fall outside a half-space, defined by a plane. Point clipping simply passes or rejects vertices; line or polygon clipping can add additional vertices depending upon how the line or polygon is clipped. In some cases, this is followed by perspective division, which makes distant geometric objects appear smaller than closer objects. Then viewport and depth (z coordinate) operations are applied. If culling is enabled and the primitive is a polygon, it then may be rejected by a culling test. Depending upon the polygon mode, a polygon may be drawn as points or lines. The results of this stage are complete geometric primitives, which are the transformed and clipped vertices with related color, depth, and sometimes texture-coordinate values and guidelines for the rasterization step. Pixel Operations While geometric data takes one path through the OpenGL rendering pipeline, pixel data takes a different route. 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. There are special pixel copy operations to copy data in the frame buffer to other parts of the frame buffer or to the texture memory. A single pass is made through the pixel transfer operations before the data is written to the texture memory or back to the frame buffer. Texture Assembly An OpenGL application may wish to apply texture images onto geometric objects to make them look more realistic. If several texture images are used, it's wise to put them into texture objects so that you can easily switch among them. Some OpenGL implementations may have special resources to accelerate texture performance. There may be specialized, high-performance texture memory. If this memory is available, the texture objects may be prioritized to control the use of this limited and valuable resource. Rasterization Rasterization is the conversion of both geometric and pixel data into fragments. Each fragment square corresponds to a pixel in the framebuffer. 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. Fragment Operations Before values are actually stored into the framebuffer, a series of operations are performed that may alter or even throw out fragments. All these operations can be enabled or disabled.

9 Display Lists:-All data, whether it describes geometry or pixels, can be saved in a display list for current or later use. When a display list is executed, the retained data is sent from the display list just as if it were sent by the application in immediate mode. Evaluators:-All geometric primitives are eventually described by vertices. Parametric curves and surfaces may be initially described by control points and polynomial functions called basis functions. Evaluators provide a method to derive the vertices used to represent the surface from the control points. The method is a polynomial mapping, which can produce surface normal, texture coordinates, colors, and spatial coordinate values from the control points. Per-Vertex Operations:- For vertex data, next is the per-vertex operations stage, which converts the vertices into primitives. Some vertex data (for example, spatial coordinates) are transformed by 4 x 4 floating-point matrices. Spatial coordinates are projected from a position in the 3D world to a position on your screen. 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 using the transformed vertex, surface normal, light source position, material properties, and other lighting information to produce a color value.

10 Primitive Assembly:- Clipping, a major part of primitive assembly, is the elimination of portions of geometry which fall outside a half-space, defined by a plane. Point clipping simply passes or rejects vertices; line or polygon clipping can add additional vertices depending upon how the line or polygon is clipped. The results of this stage are complete geometric primitives, which are the transformed and clipped vertices with related color, depth, and sometimes texture-coordinate values and guidelines for the rasterization step. Pixel Operations:- While geometric data takes one path through the OpenGL rendering pipeline, pixel data takes a different route. 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. There are special pixel copy operations to copy data in the frame buffer to other parts of the frame buffer or to the texture memory. A single pass is made through the pixel transfer operations before the data is written to the texture memory or back to the frame buffer.

11 Texture Assembly:-An OpenGL application may wish to apply texture images onto geometric objects to make them look more realistic. If several texture images are used, it's wise to put them into texture objects so that you can easily switch among them. Some OpenGL implementations may have special resources to accelerate texture performance. There may be specialized, high-performance texture memory. If this memory is available, the texture objects may be prioritized to control the use of this limited and valuable resource. Rasterization:- 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 anti-aliasing 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. Fragment Operations:- Before values are actually stored into the frame buffer, a series of operations are performed that may alter or even throw out fragments. All these operations can be enabled or disabled.

12 OpenGL Hierarchy Several levels of abstraction are provided
GL(Graphics Library) :- OpenGL on Windows and GL on most Unix/Linux System. Lowest level: vertex, matrix manipulation • Primitives - points, line, polygons • Shading and Colour • Translation, rotation, scaling • Viewing, Clipping, Texture • Hidden surface removal GLU( OpenGL Utility Library ):-Provides functionality in OpenGL core but avoids having to rewrite code, Helper functions for shapes, transformations • Viewing –perspective/orthographic • Image scaling, polygon tessellation • Sphere, cylinders, quadratic surfaces GLUT(OpenGL Utility Library ):- Provides functionality common to all window systems such as Open a window, Initialize OpenGL State, Get input from mouse and keyboard, Menus, Event-driven. Highest level: Window and interface management •Windowing toolkit (key, mouse handler, window events)

13 OpenGL and Related APIs
application program OpenGL Motif widget or similar GLUT GLX, AGL or WGL GLU GL X, Win32, Mac O/S The above diagram illustrates the relationships of the various libraries and window system components. 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. software and/or hardware AGL, GLX, WGL: glue between OpenGL and windowing systems GLU (OpenGL Utility Library) :part of OpenGL ,NURBS, tessellators, quadric shapes, GLUT (OpenGL Utility Toolkit): portable windowing API, not officially part of OpenGL

14 Preliminaries Headers Files Libraries Enumerated Types
#include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> Libraries Enumerated Types OpenGL defines numerous types for compatibility GLfloat, GLint, GLenum, etc.

15 OpenGL Commands & GLU Routine Types
Modes and Execution Primitives State Queries Coordinate Transformation GLU Routines Coloring and Lighting Texture Images Clipping Rasterization Polygon Tessellation Pixel Operations Quadric Objects Texture Mapping NURBS Curves and Surfaces Fog Error Handling Frame Buffer Operations GLX Routines Evaluators Initialization Selection and Feedback Controlling Rendering Display Lists

16 OpenGL Command Notation
void glSomeFunction {3} {bsifd} {v} (arguments); glVertex3fv( ... ) Data Type Number of components Vector the first optional term in curly braces indicates that this function takes 3 arguments. the second sets of braces indicates that this function takes 5 possible argument types b = byte, s = short, I = integer, f = float, d = double the last term in curly braces indicate that a vector form of the command also exists b - byte ub - unsigned byte s - short us - unsigned short i - int ui - unsigned int f - float d - double omit v for scalar form glVertex2f( x, y ) 2 - (x,y) 3 - (x,y,z) 4 - (x,y,z,w)

17 Some OpenGL Command Primitives Specify vertices or rectangles: void glBegin (GLenum mode); void glEnd (void); void glVertex2{sifd}{v} (TYPE x, TYPE y); void glVertex3{sifd}{v} (TYPE x, TYPE y, TYPE z); void glVertex4{sifd}{v} (TYPE x, TYPE y, TYPE z, TYPE w); void glRect{sifd} (TYPE x1, TYPE y1, TYPE x2, TYPE y2); void glRect{sifd}v (const TYPE *v1, const TYPE *v2); Specify polygon edge treatment: void glEdgeFlag (GLboolean flag); void glEdgeFlagv (const GLboolean *flag); Coordinate Transformation Transform the current matrix: void glRotate{fd} (TYPE angle, TYPE x, TYPE y, TYPE z); void glTranslate{fd} (TYPE x, TYPE y, TYPE z); void glScale{fd} (TYPE x, TYPE y, TYPE z); void glMultMatrix{fd} (const TYPE *m); void glFrustum (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far); void glOrtho (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far); Replace the current matrix: void glLoadMatrix{fd} (const TYPE *m); void glLoadIdentity (void); Manipulate the matrix stack: void glMatrixMode (GLenum mode); void glPushMatrix (void); void glPopMatrix (void);

18 Why GLUT Requires We begin with the basic elements of how to create a window. OpenGL was intentionally designed to be independent of any Specific window system. As a result, a number of the basic window operations are not provided in OpenGL. Therefore, a separate library called GLUT or OpenGL Utility Toolkit was created to provide these functions. Basically, GLUT provides the necessary tools for requesting windows to be created and providing interaction with I/O devices

19 Window Management Five routines perform tasks necessary to initialize a window. glutInit(int *argc, char **argv) initializes GLUT and processes any command line arguments .glutInit() should be called before any other GLUT routine. glutInitDisplayMode(unsigned int mode) specifies whether to use an RGBA or color-index color model. You can also specify whether you want a single- or double-buffered window. For example, if you want a window with double buffering, the RGBA color model, and a depth buffer, you might call glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH). .

20 Window Management glutInitWindowPosition(int x, int y) specifies the screen location for the upper-left corner of your window. glutInitWindowSize(int width, int size) specifies the size, in pixels, of your window. int glutCreateWindow(char *string) creates a window with an OpenGL context. It returns a unique identifier for the new window. Be warned: Until glutMainLoop() is called the window is not yet displayed

21 Program Structure Most OpenGL programs have a similar structure that consists of the following functions main(): defines the callback functions opens one or more windows with the required properties enters event loop (last executable statement) init(): sets the state variables viewing Attributes callbacks Display function Input and window functions

22 A Typical Event-Driven Program
Initialization Main Loop Event Handler Background Processing Procedure Input Processing Procedures

23 main.c #include <GL/glut.h> includes gl.h
int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow( simple ); glutDisplayFunc(mydisplay); init(); glutMainLoop(); } includes gl.h define window properties glutInit():- The arguments allows application to get command line arguments (argc and argv) and initializes system This procedure must be called before any others. It processes (and removes) command-line arguments that may be of interest to GLUT and the window system and does general . initialization of GLUT and OpenGL glutInitDisplayMode() :- This function performs initializations informing OpenGL how to set up its frame buffer. The argument to glutInitDisplayMode() is a logical-or (using the operator | ) of a number of possible options, mode Display mode, normally the bitwise OR-ing of GLUT display mode bit masks. See values below: GLUT_RGBA Bit mask to select an RGBA mode window. This is the default if neither GLUT_RGBA nor GLUT_INDEX are specified. GLUT_RGB An alias for GLUT_RGBA. GLUT_INDEX Bit mask to select a color index mode window. This overrides GLUT_RGBA if it is also specified. GLUT_SINGLE Bit mask to select a single buffered window. This is the default if neither GLUT_DOUBLE or GLUT_SINGLE are specified. GLUT_DOUBLE Bit mask to select a double buffered window. This overrides GLUT_SINGLE if it is also specified. GLUT_ACCUM Bit mask to select a window with an accumulation buffer. GLUT_ALPHA Bit mask to select a window with an alpha component to the color buffer(s). GLUT_DEPTH Bit mask to select a window with a depth buffer. GLUT_STENCIL Bit mask to select a window with a stencil buffer. glutInitWindowSize():- This command specifies the desired width and height of the graphics window. The general form is: glutInitWindowSize(int width, int height)The values are given in numbers of pixels. glutInitWindowPosition():- This command specifies the location of the upper left corner of the graphics window. The form is glutInitWindowPosition(int x, int y) where the (x, y) coordinates are given relative to the upper left corner of the display. Thus, the arguments (0, 0) places the window in the upper left corner of the display. glutCreateWindowchar():- This command actually creates the graphics window. The general form of the command is glutCreateWindowchar(*title) where title is a character string. Each window has a title, and the argument is a string which specifies the window’s title. display callback set OpenGL state enter event loop

24 init.c void init() { glClearColor (0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 1.0, 1.0); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); } black clear color opaque window fill with white viewing volume

25 mydisplay.c void mydisplay() { glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glFlush(); }

26 Features of OpenGL 3D Transformations - Rotations, scaling, translation, perspective Colour models - Values: R, G, B, alpha. Lighting - Flat shading, Gouraud shading, Phong shading Rendering -Texture mapping Modelling - non-uniform rational B-spline (NURB) curves, surfaces Others - atmospheric fog, alpha blending, motion blur OpenGL delivers fast and complete 3D hardware acceleration Today's applications and games manipulate massive amounts of data in real-time by using OpenGL hardware accelerated geometry, real-time lighting, clipping, transformations and rendering OpenGL makes real-time 3D effects possible OpenGL hardware acceleration adds detail & special effects to images without compromising performance. Examples include real-time fog, anti-aliasing, volume shadows, bump mapping, motion blur, transparency, reflections, 3D textures, volume rendering and more OpenGL is designed to support future innovations in software and hardware, The extension mechanism in OpenGL can expose radically new hardware/software features that simply never existed when OpenGL was originally conceived. So you can be confident that you will continue to get the best possible performance from your applications and games as hardware technology advances OpenGL is on every platform Ever wished that great Unix application would move to Windows or a great Windows game to Linux. Since OpenGL is fully cross-platform, it is realtively easy to port games or applications from one platform to be moved to another. This greatly expands the wealth of applications and games that support OpenGL. OpenGL is stable. High End 3D workstation & super computuer users have been enjoying OpenGL since Today, OpenGL is also the most popular and powerful 3D solution for Windows, Mac and Linux-based computers, for professional and consumer use.

27 How to Install & run OpenGL Program
Using OpenGL & GLUT in Code::Blocks Download Code::Blocks Download the GLUT bin file (first download link) from: After you download and open the GLUT bin zip file, you will need to: Copy glut32.dll to c:\windows\system, Copy glut32.lib to c:\program files\mingw\lib, and Copy glut.h to c:\program files\mingw\include\GL. These are default locations, your paths may be different. But basically, you place the .lib and .h files in the location of your compiler (in this case mingw). The .dll file goes in the windows system directory. Now you are ready to start Code::Blocks and make a new project

28 References OpenGL Reference Book

29 Thank You


Download ppt "Unit –III Graphics Programming Using OpenGL"

Similar presentations


Ads by Google