Introduction to OpenGL 2009 Autumn Animação e Visualização Tridimesional 2009/2010 1
Graphics API A software interface for graphics hardware. Provide the low-level functions to access graphics hardware directly. OpenGL / Direct3D 2
API Hierarchy Application GDI OpenGL Hardware Driver Display Device 3
What is OpenGL1/2 Industry standard. Hardware independent. OS independent. 4
What is OpenGL2/2 No commands for performing windowing tasks or obtaining user input are included. No high-level commands for describing models of 3D objects are provided. 5
OpenGL Evolution Originally controlled by an Architectural Review Board (ARB) Members included SGI, Microsoft, Nvidia, HP, 3DLabs, IBM,. Relatively stable (present version 2.1) Evolution reflects new hardware capabilities 3D texture mapping and texture objects Vertex programs Allows for platform specific features through extensions ARB replaced by Kronos 6
What OpenGL provides Draw with points, lines, and polygons. Attributes Matrix(View) Transformation Hidden Surface Removal (Z-Buffer) Light effects Gouraud Shading Texture mapping Pixels operation 7
The Buffers A buffer is a memory area in the graphics hardware for some special purposes. An OpenGL system can manipulate the four buffers: Color buffers Depth buffer (Z-Buffer) Stencil buffer Accumulation buffer 8
OpenGL Rendering Pipeline OpenGL API Calls OpenGL Command Buffer Transformation and Lighting Frame Buffer Rasterization 9
OpenGL Libraries OpenGL Library - GL The basic library to access the graphics hardware. OpenGL32 on Windows GL on most unix/linux systems (libgl.a) GLU Provide some useful utilities based on the OpenGL library. Provides functionality in OpenGL core but avoids having to rewrite code GLX / WGL / AGL OS dependent libraries to bind the OpenGL library with specific window system. GLX for X-window, WGL for win32, AGL for Apple. 10
OpenGL Utility Toolkit (GLUT) 1/3 A window system-independent toolkit to hide the complexities of differing window system APIs. Use the prefix of glut. (ex: glutdisplayfunc()) Provide following operations: Initializing and creating window Handling window and input events Drawing basic three-dimensional objects Running the program Event-driven No slide bars 11
OpenGL Utility Toolkit (GLUT) 2/3 Where can I get GLUT for Win32 and for Unix? www.opengl.org/resources/libraries/glut/ For Mac OS X: developer.apple.com/mac/library/samplecode/ glut/ 12
OpenGL Utility Toolkit (GLUT) 3/3 On Microsoft Visual C++ 6: Put glut.h into <MSVC>/include/GL/ Put glut.lib into <MSVC>/lib/ Put glut32.dll into <window>/system32/ On Microsoft Visual C++.NET: Put glut.h into <MSVC>/platformSDK/include/GL/ Put glut.lib into <MSVC>/platformSDK/lib/ Put glut32.dll into <window>/system32/ 13
Software Organization application program OpenGL Motif widget or similar GLX, AGL or WGL X, Win32, Mac O/S GLUT GLU GL software and/or hardware 14
How to Compile1/4 On Microsoft Visual C++ 6: Create a new Project with Win32 Console Application Open Project Settings dialog and add opengl32.lib glu32.lib glut32.lib into Link/Objects/library modules. Writing your OpenGL code. Compile it. 15
OpenGL Architecture Immediate Mode geometry pipeline Polynomial Evaluator Per Vertex Operations & Primitive Assembly CPU Display List Rasterization Per Fragment Operations Frame Buffer Pixel Operations Texture Memory 16
Fog Demo Nate Robins Tutors OpenGL examples http://www.xmission.com/~nate/tutors.html OpenGL sintax Several models 2D (text) and 3D drawing Image effects Graphics Windows hierarchy Menu capabilities Picking Operation 17
Drawing Geometric Objects 18
OpenGL Command Syntax -1 OpenGL commands use the prefix gl and initial capital letters for each word. OpenGL defined constants begin with GL_, use all capital letters and underscores to separate words. glvertex3f( ) OpenGL Prefix Root Command # of arguments Type of arguments 19
OpenGL Command Syntax -2 function name dimensions glvertex3f(x,y,z) belongs to GL library x,y,z are floats glvertex3fv(p) p is a pointer to an array 20
Lack of Object Orientation OpenGL is not object oriented so that there are multiple functions for a given logical function glvertex3f glvertex2i glvertex3fv Underlying storage mode is the same Easy to create overloaded functions in C++ but issue is efficiency 21
OpenGL Data Type OpenGL Type Internal representation C-Language Type Suffix GLbyte 8-bit integer signed char b GLshort 16-bit integer short s GLint, GLsizei 32-bit integer int or long i GLfloat 32-bit floating float f GLflampf pointer GLfouble 64-bit floating double d GLclampd pointer Glubyte 8-bit unsigned integer unsigned char ub GLuboolean 8-bit unsigned integer unsigned char ub GLushort 16-bit unsigned integer unsigned short us GLuint, GLenum 32-bit unsigned integer unsigned long ui GLbitfield 32-bit unsigned integer 22
State Management1/2 OpenGL is a state machine. You put it into various states (or modes) that then remain in effect until you change them. Each state variable or mode has a default value, and at any point you can query the system for each variable's current value. 23
State Management2/2 glenable(glenum); gldisable(glenum); enable and disable some state. glisenabled(glenum); Query if the specific state is enabled glgetbooleanv(); glgetintegerv(); glgetfloatv(); glgetdoublev(); glgetpointerv(); Query the specific state value. See OpenGL Programming Guide : Appendix B for all the state variables. 24
Color Representation1/2 RGBA 4 channels : Red, Green, Blue, and Alpha. Each channel has intensity from 0.0 ~ 1.0 Values outside this interval will be clamp to 0.0 or 1.0. Alpha is used in blending and transparency Ex. glcolor4f(0.0, 1.0, 0.0, 1.0); // Green glcolor4f(1.0, 1.0, 1.0, 1.0); // White 25
Color Representation2/2 Color-Index Small numbers of colors accessed by indices (8 bits) from a color map(lookup table). Ex. Less colors glindex( ); The OpenGL has no command about creating the color map, it s window system s business. glutsetcolor(); 26
Drawing Sample1/3 #include <GL/glut.h> void GL_display() { glclearcolor(0.0f, 0.0f, 0.0f, 0.0f); glclear(gl_color_buffer_bit); glbegin(gl_polygon); glcolor3f(1.0f, 1.0f, 1.0f); glvertex3f (-1.0, -1.0, 0.0); glcolor3f(1.0f, 0.0f, 0.0f); glvertex3f (1.0, -1.0, 0.0); glcolor3f(0.0f, 1.0f, 0.0f); glvertex3f (1.0, 1.0, 0.0); glcolor3f(0.0f, 0.0f, 1.0f); glvertex3f (-1.0, 1.0, 0.0); glend(); glflush(); } 27
Drawing Sample2/3 void GL_reshape(GLsizei w, GLsizei h) { glviewport(0, 0, w, h); glmatrixmode(gl_projection); glloadidentity(); if(w <= h) glortho(-2.0f, 2.0f, -2.0f * h/w, 2.0f * h/w, -2.0f, 2.0f); else glortho(-2.0f * w/h, 2.0f * w/h, -2.0f, 2.0f, -2.0f, 2.0f); glmatrixmode(gl_modelview); glloadidentity(); } void main(int argc, char** argv) { glutinit(&argc, argv); glutinitdisplaymode (GLUT_SINGLE GLUT_RGB); glutinitwindowsize (250, 250); glutinitwindowposition (100, 100); glutcreatewindow("drawing Sample"); glutdisplayfunc(gl_display); glutreshapefunc(gl_reshape); glutmainloop(); } 28
Drawing Sample3/3 29
OpenGL #defines Most constants are defined in the include files gl.h, glu.h and glut.h Note #include <GL/glut.h> should automatically include the others Examples glbegin(gl_polygon) glclear(gl_color_buffer_bit) include files also define OpenGL data types: GLfloat, GLdouble,. 30
Program Detail (GLUT)1/5 Initializing and Creating a window void glutinit(int, char**); Initialize the GLUT library. Should be called before any other GLUT routine. void glutinitdisplaymode(unsigned int); Specify a display mode for windows created. GLUT_RGBA / GLUT_INDEX GLUT_SINGLE / GLUT_DOUBLE GLUT_DEPTH, GLUT_STENCIL, GLUT_ACCUM 31
Program Detail (GLUT)2/5 glutinitwindowposition(int, int); From top-left corner of display glutinitwindowsize(int, int); Initial the window position and size when created. glutcreatewindow(char*); Open a window with previous settings. 32
Program Detail (GLUT)3/5 Handling Window and Input Events These functions are registered by user and called by GLUT simultaneously. glutdisplayfunc(void (*func)(void)); Called whenever the contents of the window need to be redrawn. Put whatever you wish to draw on screen here. Use glutpostredisplay() to manually ask GLUT to recall this display function. 33
Program Detail (GLUT)4/5 glutreshapefunc(void (*func)(int, int)); Called whenever the window is resized or moved. You should always call glviewport() here to resize your viewport. Other call back functions: glutkeyboardfunc(); glutmousefunc(); glutidlefunc(); See OpenGL Programming Guide : Appendix D for more detail 34
Program Detail (GLUT)5/5 Running the Program glutmainloop(); Enter the GLUT processing loop and never return. 35
glutreshapefunc() void GL_reshape(GLsizei w, GLsizei h) { glviewport(0, 0, w, h); glmatrixmode(gl_projection); glloadidentity(); if(w <= h) glortho(-2.0f, 2.0f, -2.0f * h/w, 2.0f * h/w, -2.0f, 2.0f); else glortho(-2.0f * w/h, 2.0f * w/h, -2.0f, 2.0f, -2.0f, 2.0f); glmatrixmode(gl_modelview); glloadidentity(); } 36
OpenGL Camera OpenGL places a camera at the origin in object space pointing in the negative z direction The default viewing volume is a box centered at the origin with a side of length 2 37
Viewing System view frustrum clipping planes clipped 38
Viewing and Projection transforms glmatrixmode (GL_MODELVIEW) glulookat()... glmatrixmode(gl_projection)... 39
Orthographic Viewing In the default orthographic view, points are projected forward along the z axis onto the plane z=0 z=0 z=0 40 40
Projection transform In OpenGL, projection is carried out by a projection matrix (transformation) There is only one set of transformation functions so we must set the matrix mode first glmatrixmode (GL_PROJECTION) Transformation functions are incremental so we start with an identity matrix and alter it with a projection matrix that gives the view volume glloadidentity(); glortho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); 41
Viewport Do not have use the entire window for the image: glviewport(x,y,w,h) Values in pixels (screen coordinates) 42
Two- and three-dimensional viewing In glortho(left, right, bottom, top, near, far) the near and far distances are measured from the camera Two-dimensional vertex commands place all vertices in the plane z=0 If the application is in two dimensions, we can use the function gluortho2d(left, right,bottom,top) In two dimensions, the view or clipping volume becomes a clipping window 43
A Drawing Survival Kit Clear the Buffers Describe Points, Lines, and Polygons Forcing Completion of Drawing 44
Clear the Buffers glclearcolor( ); glcleardepth( ); Set the current clearing values for use in clearing color buffers in RGBA mode (or depth buffer). glclear(glbitfield mask); Clear the specified buffers to their current clearing values. GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, 45
Points, Lines and Polygons1/4 Specifying a Color glcolor {34}{sifd}[v](TYPE colors); Describing Points, Lines, Polygons void glbegin(glenum mode); Marks the beginning of a vertex-data list. The mode can be any of the values in next page. void glend(); Marks the end of a vertex-data list. 46
Points, Lines and Polygons2/4 Value GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_TRIANGLES GL_TRIANGLE_STRIP GL_TRIANGLE_FAN GL_QUADS GL_QUAD_STRIP GL_POLYGON Meaning individual points pairs of vertices interpreted as individual line segments serious of connected line segments same as above, with a segment added between last and first vertices triples of vertices interpreted as triangles linked strip of triangles linked fan of triangles quadruples of vertices interpreted as four-sided polygons linked strip of quadrilaterals boundary of a simple, convex polygon 47
Points, Lines and Polygons3/4 GL_POINTS GL_LINES GL_LINE_STRIP GL_POLYGON GL_LINE_LOOP GL_TRIANGLES GL_QUAD_STRIP GL_TRIANGLE_STRIP GL_TRIANGLE_FAN 48
Points, Lines and Polygons4/4 valid calls between glbegin() and glend() glvertex*(); glnormal*(); glcolor*(); glindex*(); gltexcoord*(); glmaterial*(); Specifying Vertices glvertex{234}{sifd}[v](type coords); Specifies a vertex for use in describing a geometric object. Can only effective between a glbegin() and glend() pair. 49
Polygon Issues OpenGL will only display polygons correctly that are Simple: edges cannot cross Convex: All points on line segment between two points in a polygon are also in the polygon Flat: all vertices are in the same plane User program can check if above true OpenGL will produce output if these conditions are violated but it may not be what is desired Triangles satisfy all conditions nonsimple polygon nonconvex polygon 50
Attributes Attributes are part of the OpenGL state and determine the appearance of objects Color (points, lines, polygons) Size and width (points, lines) Stipple pattern (lines, polygons) Polygon mode Display as filled: solid color or stipple pattern Display edges Display vertices 51
Smooth Color Default is smooth shading OpenGL interpolates vertex colors across visible polygons Alternative is flat shading Color of first vertex determines fill color glshademodel (GL_SMOOTH) or GL_FLAT 52
GLUT Objects Drawing 3D objects using GLUT GLUT provides the following objects: Sphere, Cube, Torus, Icosahedron, Octahedron, Tetrahedron, Teapot, Dodecahedron, Cone, Teapot Both wireframe and solid. Ex: glutsolidsphere(1.0, 24, 24); glutwirecube(1.0); 53
Completion of Drawing glflush(); Forces previously issued OpenGL commands to begin execution. (asynchronous) glfinish(); Forces all previous issued OpenGL commands to complete. (synchronous) glutswapbuffers(); Swap front and back buffers. (double buffers) 54
Polygon Details1/2 Polygon Details glpolygonmode(glenum face, Glenum mode); Controls the drawing mode for a polygon s front and back faces. face can be GL_FRONT_AND_BACK, GL_FRONT, GL_BACK mode can be GL_POINT, GL_LINE, GL_FILL 55
Polygon Details2/2 glfrontface(glenum mode); Controls how front-facing polygons are determined. GL_CW for clockwise and GL_CCW(default) for counterclockwise glcullface(glenum mode); Indicates which polygons should be discarded before converted to screen coordinate. mode can be GL_FRONT_AND_BACK, GL_FRONT, GL_BACK 56
OpenGL Geometry Pipeline x y z w original vertex MODELVIEW PROJECTION perspective viewport matrix matrix division transformation x y z w eye eye eye eye vertices in the eye coordinate space xproj y proj z proj wproj Clipping Coordinates xdev y dev zdev 1 normalized device coordinates (foreshortened) xwin ywin zwin=dev final window coordinates 57
Transformation -2 There are three matrix stacks in OpenGL architecture MODELVIEW, PROJECTION, TEXTURE glmatrixmode( GLenum mode ); mode: GL_MODELVIEW, GL_PROJECTION, GL_TEXTURE Current matrix mode (CTM) is also a OpenGL state variable. 58
Transformation -3 Matrix Manipulation glloadidentity(); Set current matrix to the 4x4 identity matrix glloadmatrix{f,d}( const TYPE* m ); glmultmatrix{f,d}( const TYPE* m ); glpushmatrix(); glpopmatrix(); Stack operation of matrix is very useful for constructing a hierarchical structures. Ex: Render a car with four wheels. 59
Transformation -4 OpenGL built-in transformation: gltranslate{f,d}( TYPE x, TYPE, y, TYPE z ); Multiply a translation matrix into current matrix stack The effect of gltranslate() 60
Transformation -5 OpenGL built-in transformation: glrotate{f,d}( TYPE angle, TYPE x, TYPE y, TYPE z ); Multiply a rotation matrix about an arbitrary axis into current matrix stack The effect of glrotatef(45.0, 0.0, 0.0, 1.0) 61
Transformation -6 OpenGL built-in transformation: glscale{f,d}( TYPE x, TYPE y, TYPE z); Multiplies current matrix by a matrix that scales an object along axes. The effect of glscalef(2.0, -0.5, 1.0) 62
Transformation -7 Rotating First or Translating First : 63
Transformation -8a Note: By default, the viewpoint as well as objects in the scene are originally situated at the origin, and is looking down the negative z- axis, and has the positive y-axis as straight up. 64
Transformation -8b Viewing transformation Choose your viewing system Center-orientation-up system Apply glulookat Utility routine. glulookat( cx, cy, cz, atx, aty, atz, upx, upy, upz ); ( cx, cy, cz ) is the center of the camera ( atx, aty, atz ) is where the camera look at ( upx, upy, upz ) is the up vector of the camera Polar coordinate system Combine translation and two rotation. 65
Transformation -9a Projection transformation: Perspective projection glfrustum( GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far ); 66
Transformation -9b glfrustrum(xmin, xmax, ymin, ymax, zmin, zmax); Non symmetric frustrums introduce obliqueness into the projection. zmin and zmax are specified as positive distances along -z 67
Transformation -10a gluperspective( GLdouble fovy, GLdouble aspect, GLdouble near, GLdouble far ); 68
Transformation -10b gluperspective(fov, aspect, near, far); h 2 θ = tan h = 2near tan θ near 2 2 69
Transformation -11a Projection transformation: Orthogonal projection glortho( GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far ); gluortho2d( GLdouble left, GLdouble right, GLdouble bottom, GLdouble top ); A helper to create a 2D projection matrix 70
Transformation -11b glortho(xmin, xmax, ymin, ymax, zmin, zmax); 71
Transformation -12 Viewport transformation glviewport( GLint x, GLint y, GLsizei w, GLsizei h ); Initial viewport is as the same size as the window 72
Viewport to Window Transformation (x,y) = location of bottom left of viewport within the window width,height = dimension in pixels of the viewport x w = width + 2 height + 2 ( x + ) x y = ( y + 1) y n 1 w n normally we re-create the window after a window resize event to ensure a correct mapping between viewport and window dimensions 73
Shading 74 74
Objectives Learn to shade objects so their images appear three-dimensional Introduce the types of light-material interactions Build a simple reflection model---the Phong model--- that can be used with real time graphics hardware 75
Why we need shading Suppose we build a model of a sphere using many polygons and color it with glcolor. We get something like But we want 76
Shading Why does the image of a real sphere look like Light-material interactions cause each point to have a different color or shade Need to consider Light sources Material properties Surface orientation 77
Scattering Light strikes A Some scattered Some absorbed Some of scattered light strikes B Some scattered Some absorbed Some of this scattered light strikes A and so on 78
Rendering Equation The infinite scattering and absorption of light can be described by the rendering equation Cannot be solved in general Ray tracing is a special case for perfectly reflecting surfaces Rendering equation is global and includes Shadows Multiple scattering from object to object 79
Global Effects shadow translucent surface multiple reflection 80
Local vs Global Rendering Correct shading requires a global calculation involving all objects and light sources Incompatible with pipeline model which shades each polygon independently (local rendering) However, in computer graphics, especially real time graphics, we are happy if things look right Exist many techniques for approximating global effects 81
Light-Material Interaction Light that strikes an object is partially absorbed and partially scattered (reflected) The amount reflected determines the color and brightness of the object A surface appears red under white light because the red component of the light is reflected and the rest is absorbed The reflected light is scattered in a manner that depends on the smoothness and orientation of the surface 82
Light Sources General light sources are difficult to work with because we must integrate light coming from all points on the source 83
Simple Light Sources Point source Model with position and color Distant source = infinite distance away (parallel) Spotlight Restrict light from ideal point source Ambient light Same amount of light everywhere in scene Can model contribution of many sources and reflecting surfaces 84
Surface Types The smoother a surface, the more reflected light is concentrated in the direction a perfect mirror would reflected the light A very rough surface scatters light in all directions smooth surface rough surface 85
Phong Model A simple model that can be computed rapidly Has three components Diffuse Specular Ambient Uses four vectors To source To viewer Normal Perfect reflector 86
Ideal Reflector Normal is determined by local orientation Angle of incidence = angle of relection The three vectors must be coplanar r = 2 (l n ) n - l 87
Lambertian Surface Perfectly diffuse reflector Light scattered equally in all directions Amount of light reflected is proportional to the vertical component of incoming light reflected light ~cos θ i cos θ i = l n if vectors normalized There are also three coefficients, k r, k b, k g that show how much of each color component is reflected 88
Specular Surfaces Most surfaces are neither ideal diffusers nor perfectly specular (ideal reflectors) Smooth surfaces show specular highlights due to incoming light being reflected in directions concentrated close to the direction of a perfect reflection specular highlight 89
Modeling Specular Relections Phong proposed using a term that dropped off as the angle between the viewer and the ideal reflection increased I r ~ k s I cos α φ reflected shininess coef intensity incoming intensity absorption coef φ 90
The Shininess Coefficient Values of α between 100 and 200 correspond to metals Values between 5 and 10 give surface that look like plastic cos α φ -90 φ 90 91
Ambient Light Ambient light is the result of multiple interactions between (large) light sources and the objects in the environment Amount and color depend on both the color of the light(s) and the material properties of the object Add k a I a to diffuse and specular terms reflection coef intensity of ambient light 92
Distance Terms The light from a point source that reaches a surface is inversely proportional to the square of the distance between them We can add a attenuation factor of the form 1/(ad + bd +cd 2 ) to the diffuse and specular terms The constant and linear terms soften the effect of the point source Also known as depth-cueing 93
Light Sources In the Phong Model, we add the results from each light source Each light source has separate diffuse, specular, and ambient terms to allow for maximum flexibility even though this form does not have a physical justification Separate red, green and blue components Hence, 9 coefficients for each point source I dr, I dg, I db, I sr, I sg, I sb, I ar, I ag, I ab 94
Material Properties Material properties match light source properties Nine absorbtion coefficients k dr, k dg, k db, k sr, k sg, k sb, k ar, k ag, k ab Shininess coefficient α 95
Adding up the Components For each light source and each color component, the Phong model can be written (without the attenuation factor) as I =k d I d l n + k s I s (v r ) α + k a I a For each color component we add contributions from all sources 96
Modified Phong Model The specular term in the Phong model is problematic because it requires the calculation of a new reflection vector and view vector for each vertex Blinn suggested an approximation using the halfway vector that is more efficient 97
The Halfway Vector h is normalized vector halfway between l and v h = ( l + v )/ l + v 98
Using the halfway vector Replace (v r ) α by (n h ) β β is chosen to match shineness Note that halway angle is half of angle between r and v if vectors are coplanar Resulting model is known as the modified Phong or Blinn lighting model Specified in OpenGL standard 99
Example Only differences in these teapots are the parameters in the modified Phong model 100
Computation of Vectors l and v are specified by the application computer calculates r from l and n Problem is determining n how we determine n differs depending on underlying representation of surface OpenGL leaves determination of normal to application Exception for GLU quadrics and Bezier surfaces ( 101
Plane Normals Equation of plane: ax+by+cz+d = 0 plane is determined by three points p 0, p 2, p 3 or normal n and p 0 Normal can be obtained by n = (p 2 -p 0 ) (p 1 -p 0 ) 102
Normal to Sphere Implicit function f(x,y.z)=0 Normal given by gradient f f (x, y, z) = x 2 + y 2 + z 2 1 = 0 Sphere f(p)=p p -1 = 0 n = [df/dx, df/dy, df/dz] T =p 103
Parametric Form For sphere x=x(u,v)=cos u sin v y=y(u,v)=cos u cos v z= z(u,v)=sin u Tangent plane determined by vectors p/ u = [ x/ u, y/ u, z/ u]t p/ v = [ x/ v, y/ v, z/ v]t Normal given by cross product n = p/ u p/ v 104
General Case We can compute parametric normals for other simple cases Quadrics Parameteric polynomial surfaces Bezier surface patches Angel: Interactive Computer Graphics 5E Addison-Wesley 2009 105 105
Steps in OpenGL shading 1. Enable shading and select Lighting Model 2. Specify normals 3. Specify material properties 4. Specify light sources 106
Normals In OpenGL the normal vector is part of the state Set by glnormal*() glnormal3f(x, y, z); glnormal3fv(p); Usually we want to set the normal to have unit length so cosine calculations are correct Length can be affected by transformations Note that scaling does not preserved length glenable(gl_normalize) allows for auto normalization at a performance penalty 107
Normal for Triangle plane n (p - p 0 ) = 0 n p 2 n = (p 2 - p 0 ) (p 1 - p 0 ) normalize n n/ n p 0 p p 1 Note that right-hand rule determines outward face 108
Enabling Shading Shading calculations are enabled by glenable(gl_lighting) Once lighting is enabled, glcolor() ignored Must enable each light source individually glenable(gl_lighti) i=0,1.. Can choose light model parameters gllightmodeli(name,parameter) GL_LIGHT_MODEL_AMBIENT - ambient RGBA intensity of the entire scene GL_LIGHT_MODEL_LOCAL_VIEWER-how specular reflection angles are calculated GL_LIGHT_MODEL_TWO_SIDED - specifies one-sided or two-sided lighting GL_LIGHT_MODEL_COLOR_CONTROL assumes GL_SINGLE_COLOR or GL_SEPARATE_SPECULAR_COLOR 109
Light Properties gllightfv( light, property, value ); light specifies which light multiple lights, starting with GL_LIGHT0 glgetintegerv( GL_MAX_LIGHTS, &n ); properties colors position and type attenuation 110
Defining a Light Source For each light source, we can set an RGBA for the diffuse, specular, and ambient components, and for the position GL float diffuse0[]={1.0, 0.0, 0.0, 1.0}; GL float ambient0[]={1.0, 0.0, 0.0, 1.0}; GL float specular0[]={1.0, 0.0, 0.0, 1.0}; Glfloat light0_pos[]={1.0, 2.0, 3,0, 1.0}; glenable(gl_lighting); glenable(gl_light0); gllightv(gl_light0, GL_POSITION, light0_pos); gllightv(gl_light0, GL_AMBIENT, ambient0); gllightv(gl_light0, GL_DIFFUSE, diffuse0); gllightv(gl_light0, GL_SPECULAR, specular0); 111
Distance and Direction The source colors are specified in RGBA The position is given in homogeneous coordinates If w =1.0, we are specifying a finite location If w =0.0, we are specifying a parallel source with the given direction vector The coefficients in the distance terms are by default a=1.0 (constant terms), b=c=0.0 (linear and quadratic terms). Change by a= 0.80; gllightf(gl_light0, GL_CONSTANT_ATTENUATION, a); 112
Light Attenuation decrease light intensity with distance GL_CONSTANT_ATTENUATION GL_LINEAR_ATTENUATION GL_QUADRATIC_ATTENUATION f i = k c + k l 1 d + k q d 2 113
Spotlights Use gllightv to set Direction GL_SPOT_DIRECTION Cutoff GL_SPOT_CUTOFF Attenuation GL_SPOT_EXPONENT Proportional to cos α φ θ φ θ 114
Global Ambient Light Ambient light depends on color of light sources A red light in a white room will cause a red ambient term that disappears when the light is turned off OpenGL also allows a global ambient term that is often helpful for testing gllightmodelfv(gl_light_model_ambient, global_ambient) 115
Material Properties Material properties are also part of the OpenGL state and match the terms in the modified Phong model Set by glmaterialv() GLfloat ambient[] = {0.2, 0.2, 0.2, 1.0}; GLfloat diffuse[] = {1.0, 0.8, 0.0, 1.0}; GLfloat specular[] = {1.0, 1.0, 1.0, 1.0}; GLfloat shine = 100.0 glmaterialf(gl_front, GL_AMBIENT, ambient); glmaterialf(gl_front, GL_DIFFUSE, diffuse); glmaterialf(gl_front, GL_SPECULAR, specular); glmaterialf(gl_front, GL_SHININESS, shine); 116
Transparency Material properties are specified as RGBA values The A value can be used to make the surface translucent The default is that all surfaces are opaque regardless of A Later we will enable blending and use this feature 117
Front and Back Faces The default is shade only front faces which works correctly for convex objects If we set two sided lighting, OpenGL will shade both sides of a surface Each side can have its own properties which are set by using GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK in glmaterialf back faces not visible back faces visible 118
Emissive Term We can simulate a light source in OpenGL by giving a material an emissive component This component is unaffected by any sources or transformations GLfloat emission[] = 0.0, 0.3, 0.3, 1.0); glmaterialf(gl_front, GL_EMISSION, emission); 119
Efficiency Because material properties are part of the state, if we change materials for many surfaces, we can affect performance We can make the code cleaner by defining a material structure and setting all materials during initialization typedef struct materialstruct { GLfloat ambient[4]; GLfloat diffuse[4]; GLfloat specular[4]; GLfloat shineness; } MaterialStruct; We can then select a material by a pointer 120
The Mathematics of Lighting VertexColor = emission material + ambient lightmodel * ambient material + n -1 [ 1 / ( K c + K l * d + K q * d 2 ) ] i * (spotlight_effect) i * i = 0 [ ambient light * ambient material + (max {l n, 0}) * diffuse light * diffuse material + (max {h n, 0}) shininess * specular light * specular material ] i n: vertex normal l: light vector (light_pos vertex) h: half-vector - sum of the light vector with the viewing vector (view_pos vertex) 121
Light Material Tutorial 122
Moving Light Sources Light sources are geometric objects whose positions or directions are affected by the modelview matrix Depending on where we place the position (direction) setting function, we can Move the light source(s) with the object(s) Fix the object(s) and move the light source(s) Fix the light source(s) and move the object(s) Move the light source(s) and object(s) independently 123
Light Position Tutorial 124
Polygonal Shading Shading calculations are done for each vertex Vertex colors become vertex shades By default, vertex shades are interpolated across the polygon glshademodel(gl_smooth); If we use glshademodel(gl_flat); the color at the first vertex will determine the shade of the whole polygon 125
Polygon Normals Polygons have a single normal Shades at the vertices as computed by the Phong model can be almost same Identical for a distant viewer (default) or if there is no specular component Consider model of sphere Want different normals at each vertex even though this concept is not quite correct mathematically 126
Smooth Shading We can set a new normal at each vertex Easy for sphere model If centered at origin n = p Now smooth shading works Note silhouette edge 127 127
Mesh Shading The previous example is not general because we knew the normal at each vertex analytically For polygonal models, Gouraud proposed we use the average of the normals around a mesh vertex n = (n 1 +n 2 +n 3 +n 4 )/ n 1 +n 2 +n 3 +n 4 128
Gouraud and Phong Shading Gouraud Shading Find average normal at each vertex (vertex normals) Apply modified Phong model at each vertex Interpolate vertex shades across each polygon Phong shading Find vertex normals Interpolate vertex normals across edges Interpolate edge normals across polygon Apply modified Phong model at each fragment 129
Comparison If the polygon mesh approximates surfaces with a high curvatures, Phong shading may look smooth while Gouraud shading may show edges Phong shading requires much more work than Gouraud shading Until recently not available in real time systems Now can be done using fragment shaders Both need data structures to represent meshes so we can obtain vertex normals 130
A display list is a group of OpenGL commands that have been stored for later execution. Most OpenGL commands can be either stored in a display list or issued in immediate mode. 131
For example, suppose you want to draw a circle with 100 line segments drawcircle() { GLint i; GLfloat cosine, sine; glbegin(gl_polygon); for(i=0;i<100;i++){ cosine=cos(i*2*pi/100.0); sine=sin(i*2*pi/100.0); glvertex2f(cosine,sine); } glend(); } 132
This method is terribly inefficient because the trigonometry has to be performed each time the circle is rendered. Save the coordinates in a table: drawcircle() { GLint i; GLfloat cosine, sine; static GLfloat circoords[100][2]; static GLint inited=0; if(inited==0){ inited=1; for(i=0;i<100;i++){ circcoords[i][0]=cos(i*2*pi/100.0); circcoords[i][1]=sin(i*2*pi/100.0); } } glbegin(gl_polygon); for(i=0;i<100;i++) glvertex2fv(&circcoords[i][0]); glend(); } 133
Draw the circle once and have OpenGL remember how to draw it for later use. #define MY_CIRCLE_LIST 1 buildcircle() { GLint i; GLfloat cosine, sine; glnewlist (MY_CIRCLE_LIST, GL_COMPILE); glbegin(gl_polygon); for(i=0;i<100;i++){ cosine=cos(i*2*pi/100.0); sine=sin(i*2*pi/100.0); glvertex2f(cosine,sine); } glend(); glendlist (); } MY_CIRCLE_LIST is an integer index that uniquely identifies this display list. You can execute the display list later with this glcalllist() command: glcalllist(my_circle_list); 134
A display list contains only OpenGL calls. The coordinates and other variables are evaluated and copied into the display list when the list is compiled. You can delete a display list and create a new one, but you can t edit an existing display list. Display lists reside with the server and network traffic is minimized. Matrix computations, lighting models, textures, etc. Display List disadvantages: large storage; immutability of the contents of a display list. 135
Use a Display List: list.c glnewlist (listname, GL_COMPILE); glcolor3f(1.0, 0.0, 0.0); glbegin (GL_TRIANGLES); glvertex2f(0.0,0.0);glvertex2f(1.0,0.0); glvertex2f (0.0, 1.0); glend (); gltranslatef (1.5, 0.0, 0.0); glendlist (); glshademodel (GL_FLAT); void display(void) { GLuint i; glclear (GL_COLOR_BUFFER_BIT); glcolor3f(0.0, 1.0, 0.0); for (i = 0; i < 10; i++) glcalllist (listname); drawline (); /* color red; affected by the 10 translate */ glflush (); } 136
Constants are stored and won t change GLfloat color_vector[3]={0.0,0.0,0.0}; glnewlist(1,gl_compile); glcolor3fv(color_vector); glendlist(); color_vector[0]=1.0; // color will be black if you use the display list 137
Use glpushattrib() to save a group of state variables and glpopattrib() to restore glnewlist(listindex,gl_compile); glpushmatrix(); glpushattrib(gl_current_bit); glcolor3f(1.0, 0.0, 0.0); glbegin(gl_polygon); glvertex2f(0.0,0.0); glvertex2f(1.0,0.0); glvertex2f(0.0,1.0); glend(); gltranslatef(1.5,0.0,0.0); glpopattrib(); glpopmatrix(); glendlist(); The code below would draw a green, untranslated line. void display(void) { GLint i; glclear (GL_COLOR_BUFFER_BIT); glcolor3f(0.0, 1.0, 0.0); for (i = 0; i < 10; i++) glcalllist (listindex); drawline (); glflush (); } 138
Hierarchical Display Lists You can create a hierarchical display list, a display list that executes another display list. Useful for an object that s made of components which are used more than once. glnewlist(listindex,gl_compile); glcalllist(handlebars); glcalllist(frame); gltranslatef(1.0,0.0,0.0); glcalllist(wheel); gltranslatef(3.0,0.0,0.0); glcalllist(wheel); glendlist(); 139
Editable Display Lists Example editable display list: To render the polygon, call display list number 4. To edit a vertex, you need only recreate the single display list corresponding to that vertex. glnewlist(1,gl_compile); glvertex3f(v1); glendlist(); glnewlist(2,gl_compile); glvertex3f(v2); glendlist(); glnewlist(3,gl_compile); glvertex3f(v3); glendlist(); glnewlist(4,gl_compile); glbegin(gl_polygon); glcalllist(1); glcalllist(2); glcalllist(3); glend(); glendlist(); 140
Managing Display List Indices List Indices can be automatically generated: listindex=glgenlists(1); if(listindex!=0) { glnewlist(listindex,gl_compile);... glendlist(); } 141 141
Example -1 planet.c Control: A d y a ESC 142
Example -2 #include <GL/glut.h> static GLfloat year=0.0f, day=0.0f; void init() { glclearcolor(0.0, 0.0, 0.0, 0.0); } void GL_reshape(GLsizei w, GLsizei h) // GLUT reshape function { glviewport(0, 0, w, h); // viewport transformation glmatrixmode(gl_projection); // projection transformation glloadidentity(); gluperspective(60.0, (GLfloat)w/(GLfloat)h, 1.0, 20.0); glmatrixmode(gl_modelview); // viewing and modeling transformation glloadidentity(); glulookat(0.0, 3.0, 5.0, // eye 0.0, 0.0, 0.0, // center 0.0, 1.0, 0.0); // up } 143
Example -3 void GL_display() // GLUT display function { // clear the buffer glclear(gl_color_buffer_bit); } glcolor3f(1.0, 1.0, 1.0); glpushmatrix(); glutwiresphere(1.0, 20, 16); glrotatef(year, 0.0, 1.0, 0.0); gltranslatef(3.0, 0.0, 0.0); glrotatef(day, 0.0, 1.0, 0.0); glutwiresphere(0.5, 10, 8); glpopmatrix(); // swap the front and back buffers glutswapbuffers(); // the Sun // the Planet 144
Example -4 void GL_idle() // GLUT idle function { day += 10.0; if(day > 360.0) day -= 360.0; year += 1.0; if(year > 360.0) year -= 360.0; } // recall GL_display() function glutpostredisplay(); 145
Example -5 void GL_keyboard(unsigned char key, int x, int y) // GLUT keyboard function { switch(key) { case 'd': day += 10.0; if(day > 360.0) day -= 360.0; glutpostredisplay(); break; case 'y': year += 1.0; if(year > 360.0) year -= 360.0; glutpostredisplay(); break; case 'a': glutidlefunc(gl_idle); // assign idle function break; case 'A': glutidlefunc(0); break; case 27: exit(0); } } 146
Example -6 int main(int argc, char** argv) { glutinit(&argc, argv); glutinitwindowsize(500, 500); glutinitwindowposition(0, 0); glutinitdisplaymode(glut_double GLUT_RGB); glutcreatewindow("planet"); init(); glutdisplayfunc(gl_display); glutreshapefunc(gl_reshape); glutkeyboardfunc(gl_keyboard); glutmainloop(); return 0; } 147
Reference2/2 Further Reading OpenGL Programming Guide (Red Book) Interactive Computer Graphics: A To-Down Approach Using OpenGL 148
Any Question? 149