Visualization and Computer Graphics LabJacobs University
Introduction to OpenGL
Prof. Dr.-Ing. Lars Linsen
School of Engineering and ScienceJacobs University Bremen
320491: Advanced Graphics320632: Advanced Graphics Lab
Visualization and Computer Graphics LabJacobs University
1. What is OpenGL?
320491: Advanced Graphics 3
Visualization and Computer Graphics LabJacobs University
Graphics Programming
• Graphical user interface (GUI)• Windowing system
– X– Integrated in OS: Microsoft Windows, Mac OS
• Microsoft Direct3D• OpenGL (Open Graphics Library)• OpenGL 2.0 (and higher)
– GLSL (GL Shading Language)• Cg (nVidia)• HLSL (high level shader language, DirectX)• GPGPU programming: CUDA (nVidia), CTM (ATI),
OpenCL
320491: Advanced Graphics 4
Visualization and Computer Graphics LabJacobs University
What is OpenGL?
• OpenGL is a software interface for 3D computer graphics
• Originally developed by SGI (IRIS GL) since 1992 under control of ARB (Architecture Review Board)
• OpenGL specification is• hardware-independent, • window system independent and • operating system independent.
• Different implementations (as hardware and/or software)
• C library
320491: Advanced Graphics 5
Visualization and Computer Graphics LabJacobs University
OpenGL Architecture
DisplayList
PolynomialEvaluator
Per VertexOperations &
PrimitiveAssembly
Rasterization Per FragmentOperations
FrameBuffer
TextureMemory
CPU
PixelOperations
320491: Advanced Graphics 6
Visualization and Computer Graphics LabJacobs University
OpenGL as a Renderer
• Geometric primitives– points, lines, and polygons
• Image Primitives– images and bitmaps
• Separate pipeline for images and geometry– linked through texture mapping
• Rendering depends on state– colors, materials, light sources, etc.
320491: Advanced Graphics 7
Visualization and Computer Graphics LabJacobs University
Controlling current state
Setting StateglPointSize( size );glLineStipple( repeat, pattern );glShadeModel( GL_SMOOTH );
Enabling FeaturesglEnable( GL_LIGHTING );glDisable( GL_TEXTURE_2D );
320491: Advanced Graphics 8
Visualization and Computer Graphics LabJacobs University
OpenGL Command Formats
glVertex3fv( glVertex3fv( vv ))
Number ofNumber ofcomponentscomponents
2 2 -- (x,y) (x,y) 3 3 -- (x,y,z)(x,y,z)4 4 -- (x,y,z,w)(x,y,z,w)
Data TypeData Typeb b -- bytebyteub ub -- unsigned byteunsigned bytes s -- shortshortus us -- unsigned shortunsigned shorti i -- intintui ui -- unsigned intunsigned intf f -- floatfloatd d -- doubledouble
VectorVector
omit omit ““vv”” forforscalar formscalar form
glVertex2f( x, y )glVertex2f( x, y )
320491: Advanced Graphics 9
Visualization and Computer Graphics LabJacobs University
Related APIs
• AGL, GLX, WGL– glue between OpenGL and windowing systems
• GLU (OpenGL Utility Library)– part of OpenGL– NURBS, tessellators, quadric shapes, etc.
• GLUT (OpenGL Utility Toolkit)– portable windowing API– not officially part of OpenGL
320491: Advanced Graphics 10
Visualization and Computer Graphics LabJacobs University
OpenGL and Related APIs
GLUT
GLU
GL
GLX, AGLor WGL
X, Win32, Mac O/S
software and/or hardware
application program
OpenGL Motifwidget or similar
320491: Advanced Graphics 11
Visualization and Computer Graphics LabJacobs University
Preliminaries
• Headers Files• #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.
Visualization and Computer Graphics LabJacobs University
2. Getting Started
320491: Advanced Graphics 13
Visualization and Computer Graphics LabJacobs University
Getting started with OpenGL
Installation of Mesa3D: http://www.mesa3d.org
320491: Advanced Graphics 14
Visualization and Computer Graphics LabJacobs University
Getting started with OpenGL
Installation of Mesa3D: http://www.mesa3d.org
320322: Graphics and Visualization 15
Visualization and Computer Graphics LabJacobs University
Setting up GLUT
• To use GLUT its header file has to be included in the source:– #include <GL/glut.h>
• The program has to be linked against the GLUT library– For GCC just compile with -lglut– For MSVC and other of the sort add glut to the libraries in
the project options
320491: Advanced Graphics 16
Visualization and Computer Graphics LabJacobs University
GLUT Basics
• Application Structure– Configure and open window– Initialize OpenGL state– Register input callback functions
• render• resize• input: keyboard, mouse, etc.
– Enter event processing loop
320322: Graphics and Visualization 17
Visualization and Computer Graphics LabJacobs University
Initializing GLUT
• void glutInit(int argc, char **argv);– Initializes GLUT library. Should be called before any other
routine. Processes window system specific command line arguments.
• void glutInitDisplayMode(unsigned int mode);– Sets the GLUT display mode for windows created with
glutCreateWindow() – The display mode is a bitwise or combination of GLUT_RGBA
or GLUT_INDEX, GLUT_SINGLE or GLUT_DOUBLE, and any of the buffer-enabling flags GLUT_DEPTH, GLUT_STENCIL, or GLUT_ACCUM.
320322: Graphics and Visualization 18
Visualization and Computer Graphics LabJacobs University
Initializing GLUT
• void glutInitWindowSize(int width, int height);– width and height of the window
• void glutInitWindowPosition(int x, int y);– Sets the coordinates of the top-left corner
• int glutCreateWindow(char *name);– Creates a window with the name name and returns a unique
window identifying integer (handle). Useful when rendering is done in multiple windows of the same application.
320322: Graphics and Visualization 19
Visualization and Computer Graphics LabJacobs University
Handling events with GLUT
• Callback functions are registered to the corresponding event, i.e., when the respective event takes place, the function is called to handle it.
• Window events:– void glutDisplayFunc(void (*func)(void));
• The function given as argument is called whenever the window hasto be redrawn
– void glutReshapeFunc(void (*func)(int width, int height));• The function is called when the window is resized. Width and
height are the new width and height of the resized window.• When no function is specified (NULL), a default one is assigned.
320322: Graphics and Visualization 20
Visualization and Computer Graphics LabJacobs University
Handling Events with GLUT
• Input events– void glutKeyboardFunc(void (*func)(unsigned int key, int x, int y);
• The function is called when a key is pressed. Key is the ASCII of the pressed key, x and y are the mouse coordinates (window relative) at the moment the key is pressed
– void glutSpecialFunc(void (*func)(int key, int x, int y));• Triggered when a special key is pressed (F1..F12, arrows, Insert,
Home, etc.).– void glutMouseFunc(void (*func)(int button, int state, int x, int y));
• Triggered when a mouse button is pressed or released. Button is left, right or middle, state is down or up, x and y are as above.
– void glutMotionFunc(void (*func)(int x, int y));• Specifies the function that is called when the mouse is moved while
one or more buttons are pressed.
320322: Graphics and Visualization 21
Visualization and Computer Graphics LabJacobs University
Handling Events with GLUT
• Redisplaying– void glutPostRedisplay(void);
• Posts a message to the queue that redisplaying is required. At the first opportunity, the function is called.
• Idling– void glutIdleFunc(void (*func)(void));
• Function is called when nothing is happening. Sometimes this function is set to the displaying function and timed to force a certain FPS
320322: Graphics and Visualization 22
Visualization and Computer Graphics LabJacobs University
Running the Application
• Entering the process loop– void glutMainLoop(void);
320491: Advanced Graphics 23
Visualization and Computer Graphics LabJacobs University
First example: Main function (1)
320491: Advanced Graphics 24
Visualization and Computer Graphics LabJacobs University
Main function (2)
320491: Advanced Graphics 25
Visualization and Computer Graphics LabJacobs University
Reshape function
320491: Advanced Graphics 26
Visualization and Computer Graphics LabJacobs University
Keyboard function
320491: Advanced Graphics 27
Visualization and Computer Graphics LabJacobs University
Display function (1)
320491: Advanced Graphics 28
Visualization and Computer Graphics LabJacobs University
Display function (2)
320491: Advanced Graphics 29
Visualization and Computer Graphics LabJacobs University
Display function (3)
320491: Advanced Graphics 30
Visualization and Computer Graphics LabJacobs University
3. Viewing
320491: Advanced Graphics 31
Visualization and Computer Graphics LabJacobs University
Camera analogy
• 3D is just like taking a photograph (lots of photographs!)
camera
tripod model
viewingvolume
320491: Advanced Graphics 32
Visualization and Computer Graphics LabJacobs University
Camera analogy and transformations
• Projection transformations– adjust the lens of the camera
• Viewing transformations– tripod–define position and orientation of the viewing volume in the
world• Modeling transformations
– moving the model• Viewport transformations
– enlarge or reduce the physical photograph
320491: Advanced Graphics 33
Visualization and Computer Graphics LabJacobs University
Programming transformations
• Prior to rendering, view, locate, and orient:– eye/camera position– 3D geometry
• Manage the matrices– including matrix stack
• Combine (composite) transformations
320491: Advanced Graphics 34
Visualization and Computer Graphics LabJacobs University
vertex
ModelviewMatrix
ProjectionMatrix
PerspectiveDivision
ViewportTransform
Modelview
Modelview
Projection
object eye clip normalizeddevice
window
• other calculations here– material color– shade model (flat)– polygon rendering mode– polygon culling– clipping
Transformation pipeline
CPUCPU DLDL
Poly.Poly. PerVertex
PerVertex
RasterRaster FragFrag FBFB
PixelPixelTextureTexture
320491: Advanced Graphics 35
Visualization and Computer Graphics LabJacobs University
Coordinate systems and transformations
• Steps in forming an image– specify geometry (world coordinates)– specify camera (camera coordinates)– project (window coordinates)– map to viewport (screen coordinates)
• Each step uses transformations• Every transformation is equivalent to a change in coordinate
systems (frames)
320491: Advanced Graphics 36
Visualization and Computer Graphics LabJacobs University
Homogeneous coordinates
– each vertex is a column vector
– w is usually 1.0– all operations are matrix multiplications– directions (directed line segments) can be represented with w = 0.0
⎥⎥⎥⎥
⎦
⎤
⎢⎢⎢⎢
⎣
⎡
=
wzyx
vr
320491: Advanced Graphics 37
Visualization and Computer Graphics LabJacobs University
⎥⎥⎥⎥
⎦
⎤
⎢⎢⎢⎢
⎣
⎡
=
151173
141062
13951
12840
mmmmmmmmmmmmmmmm
M
3D transformations
• A vertex is transformed by 4 x 4 matrices– all affine operations are matrix multiplications– all matrices are stored column-major in OpenGL– matrices are always post-multiplied– product of matrix and vector is
vvM
320491: Advanced Graphics 38
Visualization and Computer Graphics LabJacobs University
Specifying transformations
• Specify Current Matrix StackglMatrixModeglMatrixMode( ( GL_MODELVIEWGL_MODELVIEW or or GL_PROJECTIONGL_PROJECTION ))
• Programmer has two styles of specifying transformations– specify matrices (glLoadMatrix, glMultMatrixglLoadMatrix, glMultMatrix)– specify operation (glTranslateglTranslate, , glRotateglRotate, glOrtho, glOrtho)
320491: Advanced Graphics 39
Visualization and Computer Graphics LabJacobs University
Projection Transformation
• Shape of viewing frustum
• Perspective projectiongluPerspective( fovy, aspect, zNear, zFar )glFrustum( left, right, bottom, top, zNear, zFar )
• Orthographic parallel projectionglOrtho( left, right, bottom, top, zNear, zFar )gluOrtho2D( left, right, bottom, top )
calls glOrtho with z values near zero
320322: Graphics and Visualization 40
Visualization and Computer Graphics LabJacobs University
Orthogonal projection
• void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far);– Creates a matrix for an orthographic parallel view and
multiplies it by the current matrix
320491: Advanced Graphics 41
Visualization and Computer Graphics LabJacobs University
Applying projection transformations
• Typical use (orthographic projection)glMatrixMode( GL_PROJECTION );glLoadIdentity();glOrtho( left, right, bottom, top, zNear, zFar );
•• Typical use (orthographic projection)Typical use (orthographic projection)glMatrixMode( GL_PROJECTION );glMatrixMode( GL_PROJECTION );glLoadIdentity();glLoadIdentity();
glOrtho( left, right, bottom, top, zNear, zFar );glOrtho( left, right, bottom, top, zNear, zFar );
320322: Graphics and Visualization 42
Visualization and Computer Graphics LabJacobs University
Perspective projection
• void glFrustum(GLdouble left, Gldouble right, Gldouble bottom, Gldouble top, Gldouble near, Gldouble far);– Creates a matrix for the frustrum and multiplies the current
matrix by it. Near and far are the distances to the clipping planes
320322: Graphics and Visualization 43
Visualization and Computer Graphics LabJacobs University
Perspective projection
• More intuitive:void gluPerspective(GLdouble fovy, Gldouble aspect, Gldouble near, Gldouble far);– fovy is the field of view in x-z plane. Aspect is the aspect ratio
width/height
320491: Advanced Graphics 44
Visualization and Computer Graphics LabJacobs University
Viewing transformations
• Position the camera/eye in the scene– place the tripod down; aim camera
• To “fly through” a scene– change viewing transformation and
redraw scenegluLookAt( eyex, eyey, eyez,
aimx, aimy, aimz,upx, upy, upz )
– up vector determines unique orientation– careful of degenerate positions
tripod
320491: Advanced Graphics 45
Visualization and Computer Graphics LabJacobs University
Viewing transformation
320491: Advanced Graphics 46
Visualization and Computer Graphics LabJacobs University
Modeling transformations
• Move objectglTranslate{fd}( glTranslate{fd}( x, y, zx, y, z ))
• Rotate object around arbitrary axisglRotate{fdglRotate{fd}( }( angle, x, y, zangle, x, y, z ))– angle is in degrees
• Dilate (stretch or shrink) or mirror objectglScale{fd}( glScale{fd}( x, y, zx, y, z ))
320491: Advanced Graphics 47
Visualization and Computer Graphics LabJacobs University
Viewing and modeling
• Moving camera is equivalent to moving every object in the world towards a stationary camera
• Viewing transformations are equivalent to several modeling transformations
320491: Advanced Graphics 48
Visualization and Computer Graphics LabJacobs University
Viewport Transformations
• Viewport– usually same as window size– can be used to see part of the screen to which is rendered– viewport aspect ratio should be same as projection transformation or
resulting image may be distortedglViewport( x, y, width, height )
• Viewport– usually same as window size– can be used to see part of the screen to which is rendered– viewport aspect ratio should be same as projection transformation or
resulting image may be distortedglViewportglViewport( ( x, y, width, heightx, y, width, height ))
320491: Advanced Graphics 49
Visualization and Computer Graphics LabJacobs University
Matrix Operations
• Specify Current Matrix StackglMatrixMode( GL_MODELVIEW or GL_PROJECTION )
• Other Matrix or Stack OperationsglLoadIdentity() glPushMatrix()
glPopMatrix()
• Specify Current Matrix StackglMatrixMode( glMatrixMode( GL_MODELVIEWGL_MODELVIEW or or GL_PROJECTIONGL_PROJECTION ))
• Other Matrix or Stack OperationsglLoadIdentity() glPushMatrix()glLoadIdentity() glPushMatrix()
glPopMatrix()glPopMatrix()
320322: Graphics and Visualization 50
Visualization and Computer Graphics LabJacobs University
Matrix stacks
• The matrices manipulated by all operations discussed so far are the ones that sit on the top of the matrix stack.
• When a matrix is pushed onto the stack, the current topmost matrix is duplicated, so that first and second matrices contain the same entries.
• When popping a matrix, the topmost matrix is deleted and the second one becomes the topmost one.
320322: Graphics and Visualization 51
Visualization and Computer Graphics LabJacobs University
Matrix stacks - some applications
• Modelview matrices– E.g.: Save the current position, go somewhere else, draw
something, return to the previous position, go elsewhere, draw the same thing scaled by a factor of 2, return to the initial position, …
– The stack may contain at least 32 matrices (depends on the OpenGL implementation)
• Projection matrices– E.g. useful when a text box needs to be displayed (since text is
best viewed in orthogonal projection and realistic applications are using perspective projections).
– At least 2 matrices (again depends on implementation)
Visualization and Computer Graphics LabJacobs University
4. Object Representation
320322: Graphics and Visualization 53
Visualization and Computer Graphics LabJacobs University
OPenGL primitive types
Points:
320322: Graphics and Visualization 54
Visualization and Computer Graphics LabJacobs University
OPenGL primitive types
Line segments & sequences thereof:
320322: Graphics and Visualization 55
Visualization and Computer Graphics LabJacobs University
OpenGL primitive types
Convex simple polygons & meshes:
320491: Advanced Graphics 56
Visualization and Computer Graphics LabJacobs University
Using OpenGL primitives
• Primitives are specified usingglBegin( glBegin( primType primType ););
glEnd();glEnd();
– primType is any of the primitive types and determines how vertices are combined.
GLfloat red, green, blue;GLfloat red, green, blue;Glfloat coords[3];Glfloat coords[3];glColor3f( red, green, blue );glColor3f( red, green, blue );glBeginglBegin( ( primType primType ););for ( i = 0; i < nVerts; ++i ) { for ( i = 0; i < nVerts; ++i ) { glVertex3fv( coords );glVertex3fv( coords );}}glEnd();glEnd();
320491: Advanced Graphics 57
Visualization and Computer Graphics LabJacobs University
Using OpenGL Primitives
320491: Advanced Graphics 58
Visualization and Computer Graphics LabJacobs University
Using OpenGL Primitives
glBegin(GL_POLYGON); glVertex2f(0.0, 0.0); glVertex2f(0.0, 3.0); glVertex2f(4.0, 3.0); glVertex2f(6.0, 1.5); glVertex2f(4.0, 0.0);
glEnd();
320491: Advanced Graphics 59
Visualization and Computer Graphics LabJacobs University
GLUT objects
• void glutWireSphere(GLdouble radius, GLint slices, GLint stacks);void glutSolidSphere(GLdouble radius, GLint slices, GLint stacks);
• void glutWireCube(GLdouble size); void glutSolidCube(GLdouble size);
• void glutWireTorus(GLdouble innerRadius, GLdouble outerRadius,GLint nsides, GLint rings);
• void glutSolidTorus(GLdouble innerRadius, GLdouble outerRadius,GLint nsides, GLint rings);
320491: Advanced Graphics 60
Visualization and Computer Graphics LabJacobs University
GLUT objects
320491: Advanced Graphics 61
Visualization and Computer Graphics LabJacobs University
GLUT objects
320491: Advanced Graphics 62
Visualization and Computer Graphics LabJacobs University
GLUT objects
• void glutWireIcosahedron(void); void glutSolidIcosahedron(void);
• void glutWireOctahedron(void); void glutSolidOctahedron(void);
• void glutWireTetrahedron(void); void glutSolidTetrahedron(void);
• void glutWireDodecahedron(GLdouble radius); void glutSolidDodecahedron(GLdouble radius);
320491: Advanced Graphics 63
Visualization and Computer Graphics LabJacobs University
GLUT objects
• void glutWireCone(GLdouble radius, GLdouble height, GLint slices,GLint stacks); void glutSolidCone(GLdouble radius, GLdouble height, GLint slices,GLint stacks);
• void glutWireTeapot(GLdouble size); void glutSolidTeapot(GLdouble size);
320491: Advanced Graphics 64
Visualization and Computer Graphics LabJacobs University
GLUT objects
Visualization and Computer Graphics LabJacobs University
5. Displaying
320491: Advanced Graphics 66
Visualization and Computer Graphics LabJacobs University
Rasterization
CPUCPU DLDL
Poly.Poly. PerVertex
PerVertex
RasterRaster FragFrag FBFB
PixelPixel
TextureTexture
320491: Advanced Graphics 67
Visualization and Computer Graphics LabJacobs University
Double Buffering
12
48
16
12
48
16FrontBuffer
BackBuffer
Display
320491: Advanced Graphics 68
Visualization and Computer Graphics LabJacobs University
Animation Using Double Buffering
Request a double buffered color bufferglutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE );
Clear color bufferglClear( GL_COLOR_BUFFER_BIT );
Render sceneRequest swap of front and back buffers
glutSwapBuffers();
Repeat steps 2 - 4 for animation
320491: Advanced Graphics 69
Visualization and Computer Graphics LabJacobs University
An Updated Program Template (cont.)
• void drawScene( void )• {
GLfloat vertices[] = { … };GLfloat colors[] = { … };glClear( GL_COLOR_BUFFER_BIT);glBegin( GL_TRIANGLE_STRIP );
/* calls to glColor*() and glVertex*() */glEnd();glutSwapBuffers();
• }
• void drawScene( void )• {
GLfloat vertices[] = { … };GLfloat colors[] = { … };glClear( GL_COLOR_BUFFER_BIT);glBegin( GL_TRIANGLE_STRIP );
/* calls to glColor*() and glVertex*() */glEnd();glutSwapBuffers();
• }
320491: Advanced Graphics 70
Visualization and Computer Graphics LabJacobs University
Antialiasing
• Removing the Jaggies• glEnable( mode )
• GL_POINT_SMOOTH• GL_LINE_SMOOTH• GL_POLYGON_SMOOTH
– alpha value computed by computingsub-pixel coverage
– available in both RGBA and colormap modes
320491: Advanced Graphics 71
Visualization and Computer Graphics LabJacobs University
Full Scene Antialiasing : Jittering the view
• Each time we move the viewer, the image shifts– Different aliasing artifacts in each image– Averaging images using accumulation
buffer averages outthese artifacts
320491: Advanced Graphics 72
Visualization and Computer Graphics LabJacobs University
Blending
• Combine pixels with what’s in alreadyin the framebuffer
• glBlendFunc( src, dst )
FramebufferFramebufferPixelPixel((dstdst))
BlendingEquation
BlendingEquation
FragmentFragment((srcsrc))
BlendedBlendedPixelPixel
pfr CdstCsrcCvvv
+=
320491: Advanced Graphics 73
Visualization and Computer Graphics LabJacobs University
Accumulation Buffer
• glAccum( op, value )– operations
• within the accumulation buffer: GL_ADD, GL_MULT• from read buffer: GL_ACCUM, GL_LOAD• transfer back to write buffer: GL_RETURN
– glAccum(GL_ACCUM, 0.5) multiplies each value in write buffer by 0.5 and adds to accumulation buffer
320491: Advanced Graphics 74
Visualization and Computer Graphics LabJacobs University
Accumulation Buffer
• Problems of compositing into color buffers– limited color resolution
• clamping• loss of accuracy
– Accumulation buffer acts as a “floating point” color buffer• accumulate into accumulation buffer• transfer results to frame buffer
320491: Advanced Graphics 75
Visualization and Computer Graphics LabJacobs University
Multi-pass Rendering
• Blending allows results from multiple drawing passes to be combined together– enables more complex rendering algorithms
Example of bump-mappingdone with a multi-pass
OpenGL algorithm
320491: Advanced Graphics 76
Visualization and Computer Graphics LabJacobs University
Depth Buffering
12
48
16
12
48
16ColorBuffer
DepthBuffer
Display
320491: Advanced Graphics 77
Visualization and Computer Graphics LabJacobs University
Depth Buffering Using OpenGL
Request a depth bufferglutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
Enable depth bufferingglEnable( GL_DEPTH_TEST );
Clear color and depth buffersglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
Render sceneSwap color buffers
Request a depth bufferglutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
Enable depth bufferingglEnable( GL_DEPTH_TEST );
Clear color and depth buffersglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
Render sceneSwap color buffers
Visualization and Computer Graphics LabJacobs University
6. Colors & Shading
320491: Advanced Graphics 79
Visualization and Computer Graphics LabJacobs University
Specifying Geometric Primitives
320491: Advanced Graphics 80
Visualization and Computer Graphics LabJacobs University
How OpenGL Simulates Lights
• Phong lighting model– Computed at vertices
• Lighting contributors– Surface material properties– Light properties– Lighting model properties
320491: Advanced Graphics 81
Visualization and Computer Graphics LabJacobs University
Surface Normals
• Normals define how a surface reflects light• glNormal3f( x, y, z )
– Current normal is used to compute vertex’s color– Use unit normals for proper lighting
• scaling affects a normal’s lengthglEnable( GL_NORMALIZE )
orglEnable( GL_RESCALE_NORMAL )
320491: Advanced Graphics 82
Visualization and Computer Graphics LabJacobs University
Material Properties
• Define the surface properties of a primitive• glMaterialfv( face, property, value );
– separate materials for front and back
GL_DIFFUSE Base color
GL_SPECULAR Highlight Color
GL_AMBIENT Low-light Color
GL_EMISSION Glow Color
GL_SHININESS Surface Smoothness
320491: Advanced Graphics 83
Visualization and Computer Graphics LabJacobs University
Light Properties
• glLightfv( light, property, value );– light specifies which light
• multiple lights, starting with GL_LIGHT0glGetIntegerv( GL_MAX_LIGHTS, &n );
– properties• colors• position and type• attenuation
320491: Advanced Graphics 84
Visualization and Computer Graphics LabJacobs University
Light Colors
• Light color properties– GL_AMBIENT– GL_DIFFUSE– GL_SPECULAR
• Light color properties– GL_AMBIENT– GL_DIFFUSE– GL_SPECULAR
320491: Advanced Graphics 85
Visualization and Computer Graphics LabJacobs University
Types of Lights
• OpenGL supports two types of Lights– Local (Point) light sources– Infinite (Directional) light sources
• Type of light controlled by w coordinate
( )( )w
zw
yw
xwzyxw
at positioned Light Local along directed LightInfinite
00
≠=
320491: Advanced Graphics 86
Visualization and Computer Graphics LabJacobs University
Attenuation
• Light attenuation– decrease light intensity with distance
• GL_CONSTANT_ATTENUATION• GL_LINEAR_ATTENUATION• GL_QUADRATIC_ATTENUATION
2
1dkdkk
fqlc
i ++=
320491: Advanced Graphics 87
Visualization and Computer Graphics LabJacobs University
Turning on the Lights
• Flip each light’s switchglEnable( GL_LIGHTn );
• Turn on the powerglEnable( GL_LIGHTING );
320491: Advanced Graphics 88
Visualization and Computer Graphics LabJacobs University
Light & Material
320491: Advanced Graphics 89
Visualization and Computer Graphics LabJacobs University
Advanced Lighting Features
• Spotlights– localize lighting affects
• GL_SPOT_DIRECTION
• GL_SPOT_CUTOFF• GL_SPOT_EXPONENT
320491: Advanced Graphics 90
Visualization and Computer Graphics LabJacobs University
Shading
• Setting StateglShadeModel( GL_SMOOTH | GL_FLAT);
• Setting StateglShadeModelglShadeModel( ( GLGL__SMOOTHSMOOTH | GL_FLAT);| GL_FLAT);
320491: Advanced Graphics 91
Visualization and Computer Graphics LabJacobs University
8. Textures
320491: Advanced Graphics 92
Visualization and Computer Graphics LabJacobs University
• Apply a 1D, 2D, or 3D image to geometricprimitives
• Apply a 1D, 2D, or 3D image to geometricprimitives
Texture Mapping
CPUCPU DLDL
Poly.Poly. PerVertex
PerVertex
RasterRaster FragFrag FBFB
PixelPixelTextureTexture
320491: Advanced Graphics 93
Visualization and Computer Graphics LabJacobs University
Texture Mapping and the OpenGL Pipeline
geometry pipelinevertices
pixel pipelineimagerasterizer
• Images and geometry flow through separate pipelines that join at the rasterizer– “complex” textures do not affect geometric complexity
320491: Advanced Graphics 94
Visualization and Computer Graphics LabJacobs University
Applying Textures
• Three stepsspecify texture
• read or generate image• assign to texture• enable texturing
assign texture coordinates to verticesspecify texture parameters
• wrapping, filtering
320491: Advanced Graphics 95
Visualization and Computer Graphics LabJacobs University
Texture Objects
• Like display lists for texture images– one image per texture object– may be shared by several graphics contexts
• Generate texture namesglGenTextures( n, *texIds );
320491: Advanced Graphics 96
Visualization and Computer Graphics LabJacobs University
Texture Objects (cont.)
• Create texture objects with texture data and state• Bind textures before using
glBindTexture( target, id );
320491: Advanced Graphics 97
Visualization and Computer Graphics LabJacobs University
• Define a texture image from an array of texels in CPU memory
glTexImage2D( target, level, components,w, h, border, format, type, *texels );
Specify Texture Image
320491: Advanced Graphics 98
Visualization and Computer Graphics LabJacobs University
• Based on parametric texture coordinates• glTexCoord*() specified at each vertex
s
t 1, 10, 1
0, 0 1, 0
(s, t) = (0.2, 0.8)
(0.4, 0.2)
(0.8, 0.4)
A
B C
a
bc
Texture Space Object Space
Mapping a Texture
320491: Advanced Graphics 99
Visualization and Computer Graphics LabJacobs University
Example
// Loading a Texture, specifying propertiesglGenTextures(1, &texName);glBindTexture(GL_TEXTURE_2D, texName);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, Image_Buffer);// later while describing polygons...
glTexCoord2f(0.0, 0.0); glVertex3f(-2.0, -1.0, 0.0);glTexCoord2f(0.0, 1.0); glVertex3f(-2.0, 1.0, 0.0);…
320491: Advanced Graphics 100
Visualization and Computer Graphics LabJacobs University
Example
320491: Advanced Graphics 101
Visualization and Computer Graphics LabJacobs University
Applying Textures
– specify textures in texture objects– set texture filter – set texture function – set texture wrap mode– set optional perspective correction hint– bind texture object – enable texturing– supply texture coordinates for vertex
• coordinates can also be generated
– specify textures in texture objects– set texture filter – set texture function – set texture wrap mode– set optional perspective correction hint– bind texture object – enable texturing– supply texture coordinates for vertex
• coordinates can also be generated
320491: Advanced Graphics 102
Visualization and Computer Graphics LabJacobs University
• Filter Modes– minification or magnification– special mipmap minification filters
• Wrap Modes– clamping or repeating (tiling)
• Texture Functions– how to mix primitive’s color with texture’s color
• blend, modulate or replace texels
Texture Application Methods
320491: Advanced Graphics 103
Visualization and Computer Graphics LabJacobs University
Filter Modes
Texture PolygonMagnification Minification
PolygonTexture
Example:glTexParameteri( glTexParameteri( target, type, modetarget, type, mode ););
320491: Advanced Graphics 104
Visualization and Computer Graphics LabJacobs University
Mipmapped Textures
• Mipmap allows for prefiltered texture maps of decreasing resolutions• Lessens interpolation errors for smaller textured objects• Declare mipmap level during texture definition
glTexImage*D( glTexImage*D( GL_TEXTURE_*D, level, GL_TEXTURE_*D, level, …… ))
• GLU mipmap builder routinesgluBuild*DMipmaps( gluBuild*DMipmaps( …… ))
• OpenGL 1.2 introduces advanced LOD controls
320491: Advanced Graphics 105
Visualization and Computer Graphics LabJacobs University
Wrapping Mode
• Example:glTexParameteri( GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP )glTexParameteri( GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_REPEAT )
texture
s
t
GL_CLAMPwrapping
GL_REPEATwrapping
320491: Advanced Graphics 106
Visualization and Computer Graphics LabJacobs University
Texture Functions
• Controls how texture is applied• glTexEnv{fi}[v]( GL_TEXTURE_ENV, prop, param )
• GL_TEXTURE_ENV_MODE modes– GL_MODULATE– GL_BLEND– GL_REPLACE
• Set blend color with GL_TEXTURE_ENV_COLOR
320491: Advanced Graphics 107
Visualization and Computer Graphics LabJacobs University
Perspective Correction Hint
• Texture coordinate and color interpolation– either linearly in screen space– or using depth/perspective values (slower)
• Noticeable for polygons “on edge”• glHint( GL_PERSPECTIVE_CORRECTION_HINT, hint )
where hint is one of • GL_DONT_CARE• GL_NICEST• GL_FASTEST