Graphics Programming Throw Open GL
Graphics Programming Throw Open GL
Introduction to OpenGL
Outline
What is OpenGL OpenGL Rendering Pipeline OpenGL Utility Toolkits OpenGL Coding Framework OpenGL API
Graphics System
Function calls Data
Output Input
Graphics API
What is OpenGL
OpenGL
A software interface to graphics hardware A 3D graphics rendering API (>120 functions) Hardware independent Very fast (a standard to be accelerated) Portable
http://www.opengl.org
A History of OpenGL
Was SGIs Iris GL OpenGL Open standard allowing for wide range hardware platforms OpenGL v1.0 (1992) OpenGL v1.1 (1995) OpenGL v1.4 (latest) Governed by OpenGL Architecture Review Board (ARB) Mesa an Open source (http://www.mesa3d.org)
Graphics Process
Geometric Primitives
Rendering Rendering
Image Primitives
Frame Buffer
OpenGL Architecture
Window Management
OpenGL is window and operating system independent OpenGL does not include any functions for window management, user interaction, and file I/O Host environment is responsible for window management
GLUT
OpenGL Window Interface/Utility toolkit
AUX
OpenGL Utility Toolkit
GLU
an auxiliary library that handles a variety of graphics accessory functions
GLUT/AUX
utility toolkits that handle window managements
Library File
opengl32.lib (PC) -lgl (UNIX) glu32.lib (PC) -lglu
Header File
gl.h glu.h
Note
core library handles a variety of accessory functions window managements
Utility toolkits
glut.h glaux.h
Environment Setup
All of our discussions will be presented in C/C++ language Use GLUT library for window managements Files needed gl.h, glu.h, glut.h opengl32.lib, glu32.lib, glut32.lib Go to http://www.opengl.org download files Follow the Setup instruction to configure proper path
Usage
Include the necessary header files in your code
#include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> // core, the only thing is required // handles accessory functions // handles window managements
Usage
Link the necessary Libraries to your code
Link GL library
Link opengl32.lib (PC), or -lgl (UNIX)
Representation
8-bit integer 16-bit integer 32-bit integer 32-bit float 64-bit float 8-bit unsigned integer 16-bit unsigned short 32-bit unsigned integer
As C Type
signed char short long float double unsigned char unsigned short unsigned long
f: the argument is float type i: the argument is integer type v: the argument requires a vector
A Sample Program
void main (int argc, char **argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (500, 500); glutCreateWindow (My First Program"); myinit (); glutDisplayFunc ( display ); glutReshapeFunc ( resize ); glutKeyboardFunc ( key ); glutMainLoop (); }
1 2 3 4
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // display model glutInitWindowSize (500, 500); glutCreateWindow (My First Program"); } // window size // create window
GLUT initialization
glutInit (int argc, char ** argv) Display model glutInitDisplayMode (unsigned int mode) Window size and position glutInitWindowSize (int width, int height) glutInitWindowPosition(int x, int y) Create window glutCreateWindow (char *name);
Callback Functions
Callback Function
Routine to call when something happens - window resize, redraw, user input, etc
Rendering Callback
Its here that does all of your OpenGL rendering
void display( void ) { typedef GLfloat point2[2]; point2 vertices[3]={{0.0, 0.0}, {250.0, 500.0}, {500.0, 0.0}}; int i, j, k; int rand(); glClear(GL_COLOR_BUFFER_BIT); for( k=0; k<5000; k++) }
Lets go Inside
OpenGL API
Geometric Primitives Color Mode Managing OpenGLs State Transformations Lighting and shading Texture mapping
Transformation
Rotation, size, perspective in 3D coordinate space
Color mode
RGB, RGBA, Color index
Buffering
Double buffering, Z-buffering, Accumulation buffer
Texture mapping
Geometric Primitives
GL_POINTS
GL_LINES
GL_LINE_STRIP
GL_LINE_LOOP
GL_POLYGON
GL_QUADS
GL_TRIANGLES GL_TRIANGLE_FAN
Geometry Commands
glBegin(GLenum type) marks the beginning of a vertex-data list that describes a geometric primitives
glEnd (void)
marks the end of a vertex-data list
glVertex*()
specifies vertex for describing a geometric object
Example
void drawSquare (GLfloat *color) { glColor3fv ( color ); glBegin(GL_POLYGON); glVertex2f ( 0.0, 0.0 ); glVertex2f ( 1.0, 0.0 ); glVertex2f ( 1.1, 1.1 ); glVertex2f ( 0.0, 1.0 ); glEnd(); }
How to draw
Attributes
colors, lighting, shading, texturing, etc.
Attributes
An attribute is any property that determines how a geometric primitives is to be rendered Each time, OpenGL processes a vertex, it uses data stored in its internal attribute tables to determine how the vertex should be transformed, rendered or any of OpenGLs other modes
Example
glPointSize(3.0); glShadeModel(GL_SMOOTH); glBegin(GL_LINE); glColor4f(1.0, 1.0, 1.0, 1.0); glVertex2f(5.0, 5.0); glColor3f(0.0, 1.0, 0.0); glVertex2f(25.0, 5.0); glEnd();
OpenGL Color
There are two color models in OpenGL
RGB Color (True Color) Indexed Color (Color map)
The type of window color model is requested from the windowing system. OpenGL has no command to control
Color Cube
RGB Color
R, G, B components are stored for each pixel With RGB mode, each pixels color is independent of each other
RGB Color
Red
Green
Blue
For example: 4-bit color 24 = 16 colors 8-bit color 8 2 = 256 colors 24-bit color 24 2 = 16.77 million colors
Alpha Component
Alpha value A value indicating the pixels opacity
Zero usually represents totally transparent and the maximum value represents completely opaque
Alpha buffer
Hold the alpha value for every pixel Alpha values are commonly represented in 8 bits, in which case transparent to opaque ranges from 0 to 255
glClearColor(r, g, b, a)
sets current color for cleaning color buffer
glutInitDisplayMode(mode)
specify either an RGBA window (GLUT_RGBA ), or a color indexed window (GLUT_INDEX )
Example
glutInitDisplayMode (GLUT_RGBA); glClearColor(1.0, 1.0, 1.0, 1.0); void drawLine (GLfloat *color) { glColor3fv ( color ); glBegin(GL_LINE); glVertex2f ( 0.0, 0.0 ); glVertex2f ( 1.0, 0.0 ); glEnd(); }
Indexed Color
Historically, color-index mode was important because it required less memory Use Color-map (lookup table) With color-index mode, each pixel with same index stored in its bit-planes shares the same color-map location
Red 0 120
Green 0 123
Blue 0 187
RGBA model
glClearIndex(Glfloat index)
sets current color for cleaning color buffer.
Shading Model
Green
Red
Blue
(0, 0, 0) Black
Shading Model
Green
Red
Blue
Flat shading: the color of one particular vertex of an independent primitive is duplicated across all the primitives vertices to render that primitive. Smooth shading: the color at each vertex is treated individually. The colors of interior pixels are interpolated.
Attributes
Example
glEnable(GL_LIGHTING); glShadeModel(GL_SMOOTH); glBegin(GL_LINE); glColor3f(1.0, 1.0, 1.0); glVertex2f(5.0, 5.0); glColor3f(0.0, 1.0, 0.0); glVertex2f(25.0, 5.0); glEnd(); glDisable(GL_LIGHTING);
OpenGL Transformations
View direction
Graphics Pipeline
Object
Object Coordinates
Transformation Object -> World Transformation World -> Viewport Clipping Screen Coordinates
World
World Coordinates
Viewport
Viewport Coordinates
Camera Analogy
The graphics transformation process is analogous to taking a photograph with a camera
- Position camera - Place objects - Adjust camera - Produce photograph
Modeling transformation
Positioning and moving the model.
Projection transformation
Adjusting the lens of the camera.
Viewport transformation
Enlarging or reducing the physical photograph.
Transformations in OpenGL
Transformations are specified by matrix operations. Desired transformation can be obtained by a sequence of simple transformations that can be concatenated together. Transformation matrix is usually represented by 4x4 matrix (homogeneous coordinates). Provides matrix stacks for each type of supported matrix to store matrices.
Programming Transformations
In OpenGL, the transformation matrices are part of the state, they must be defined prior to any vertices to which they are to apply. In modeling, we often have objects specified in their own coordinate systems and must use transformations to bring the objects into the scene. OpenGL provides matrix stacks for each type of supported matrix (model-view, projection, texture) to store matrices.
Steps in Programming
Define matrices:
Viewing/modeling, projection, viewport
Composite transformations
If change the CTM, we change the state of the system. CTM is a 4 x 4 matrix that can be altered by a set of functions.
Viewing-Modeling Transformation
If given an object, and I want to render it from a viewpoint, what information do I have to have?
Viewing position
Viewing Position
y
R, T x z x
Camera
Translation Rotation
In the default position, the camera is at the origin, looking down the negative z-axis
+Z
+X
If we use OpenGL
Look-At Function
gluLookAt (eyex, eyey, eyez, atx, aty, atz, upx, upy, upz ) Define a viewing matrix and multiplies it to the right of the current matrix.
Specifying Matrix
Specify current matrix mode Modify current matrix Load current matrix Multiple current matrix
Specifying Operations
Three OpenGL operation routines for modeling transformations: Translation Scale Rotation
Recall
Three elementary 3D transformations
1 0 T ( dx, dy , d z ) = 0 0 sx 0 = S (sx , s y , s z) 0 0 0 1 0 0 0 sy 0 0 0 0 1 0 d x d y d z 1 0 0 sz 0 0 0 0 1
Translation:
Scale:
Recall
Rotation Rx ( )
1 0 0 0 cos sin Rx ( ) = 0 sin cos 0 0 0 cos 0 Ry( ) = sin 0 0 sin 1 0 0 cos 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 1
Rotation Ry ( )
Rotation Rz ( )
Example
Lets examine an example: Rotation about an arbitrary point
Question: Rotate a object for a 45.0-degree about the line through the origin and the point (1.0, 2.0, 3.0) with a fixed point of (4.0, 5.0, 6.0).
OpenGL Implementation
glMatrixMode (GL_MODEVIEW); glLoadIdentity (); glTranslatef (4.0, 5.0, 6.0); glRotatef (45.0, 1.0, 2.0, 3.0); glTranslatef (-40.0, -5.0, -6.0);
Order of Transformations
The transformation matrices appear in reverse order to that in which the transformations are applied. In OpenGL, the transformation specified most recently is the one applied first.
Order of Transformations
In each step:
C <= I C <= CT(4.0, 5.0, 6.0) C <= CR(45, 1.0, 2.0, 3.0) C < = CT(-4.0, -5.0, -6.0)
Finally
C = T(4.0, 5.0, 6.0) CR(45, 1.0, 2.0, 3.0) CT(-4.0, -5.0, -6.0) Write it Read it
Matrix Stacks
OpenGL uses matrix stacks mechanism to manage transformation hierarchy. OpenGL provides matrix stacks for each type of supported matrix to store matrices.
Model-view matrix stack Projection matrix stack Texture matrix stack
Matrix Stacks
Current matrix is always the topmost matrix of the stack We manipulate the current matrix is that we actually manipulate the topmost matrix. We can control the current matrix by using push and pop operations.
Bottom
Projection Transformation
Projection & Viewing Volume Projection Transformation Viewpoint Transformation
X Positive
(50, 50)
Y Positive
(0, 0)
Positive X
Remember: the Y coordinates of OpenGL screen is the opposite of Windows screen. But same as in the XWindows system.
Orthographic Projection
Vertexes of an object are projected towards infinity Points projected outside view volume are clipped out Distance does not change the apparent size of an object Image
Clipped out
Viewing rectangle
Viewing volume
Viewing volume
Hidden-Surface Removal
z-buffer algorithm - Image-space check - The worst-case complexity is proportional to the number of polygons - Requires a depth or z buffer to store the information as polygons are rasterized
Viewpoint
z1
z2
Hidden-Surface Removal
glEnable(GL_DEPTH_TEST) glDisable(GL_DEPTH_TEST) Enable/disable z (depth) buffer for hiddensurface removal
Remember to Initialize
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RBG|GLUT_DEPTH);
You can also clear the depth buffer (as we did for color buffer)
Viewing a 3D world
View up
Aspect Ratio =
ViewRight ViewUp
View right
Viewpoint
Viewpoint
The region within the window that will be used for drawing the clipping area By default, it is set to the entire rectangle of the window that is opened Measured in the window coordinates, which reflect the position of pixels on the screen related to the lower-left corner of the window
Viewpoint Transformation
h w w A viewpoint is defined as half the size of the window A viewpoint is defined as the same size as the window h
Aspect Ratio
The Aspect Ratio of a rectangle is the ratio of the rectangles width to its height: e.g. Aspect Ratio = width/height Viewport aspect ratio should be same as projection transformation, or resulting image may be distorted.
Viewpoint Commands
glViewport( x, y, width, height ) Defines a pixel rectangle in the window into which the final image is mapped (x, y) specifies the lower-left corner of the viewport (width, height) specifies the size of the viewport rectangle
Lighting
Point light source - approximates the light source as a 3D point in space. Light rays emanate in all directions. Distributed light source - approximates the light source as a 3D object. Light rays usually emanate in specific directions. Spotlights - characterized by a narrow range of angles through which light is emitted. Ambient light - provide uniform illumination throughout the environment. It represents the approximate contribution of the light to the general scene, regardless of location of light and object. (Background Light)
Light Model
Ambient The combination of light reflections from various surfaces to produce a uniform illumination. Background light. Diffuse Uniform light scattering of light rays on a surface. Proportional to the amount of light that hits the surface. Depends on the surface normal and light vector. Sepecular Light that gets reflected. Depends on the light ray, the viewing angle, and the surface normal.
Light Model
Light at a pixel from a light = Ambient + Diffuse + Specular
l =0
Shading
Flat Shading
Calculate one lighting calculation (pick a vertex) per triangle Color the entire triangle the same color
Gouraud Shading
Calculate three lighting calculations (the vertices) per triangle Linearly interpolate the colors as you scan convert
Phong Shading
While do scan convert, linearly interpolate the normals. With the interpolated normal at each pixel, calculate the lighting at each pixel
Lighting in OpenGL
OpenGL supports the four types of light sources. OpenGL allows at least eight light sources set in a program. We must specify and enable individually (as exactly required by the Phong model)
glLight*(Glenum light, Glenum pname, TYPE param) Create the light specified by light, which can be GL_light0, GL_light1,GL_light7. pname indicates the properties of light that will be specified with param.
Two-sided Lighting
glLightModelfi (GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
Keep in mind that texture mapping works only in RGBA mode. Texture mapping results in colorindex mode are undefined.
Note: both width and height must have the form 2m+2b, where m is nonnegative integer, and b is the value of board.
Texture Object
Texture objects are an important new feature since OpenGL 1.1. A texture object stores data and makes it readily available. To use texture objects for your texture data, take these steps:
Generate texture names. Initially bind (create) texture objects to texture data, including the image arrays and texture properties. Bind and rebind texture objects, making their data currently available for rendering texture models.
When using it first time, a new texture object is created. When binding to previously created texture object, that texture object becomes active.
Ex:
glBindTexture(GL_TEXTURE_2D, name);
Delete n texture object, named by elements in the array textureNames. The freed texture names may now be reused.
Set various parameters that control how a texture is treated as its applied or stored in a texture object.
How to control texture mapping and rendering?
(s, t)
(u, v)
(x, y)
(s, t)
(u, v)
(x, y)
Set the current texturing function. We can use directly the texture colors to paint the object, or use the texture values to modulate or blend the color in the texture map with the original color of object.
Ex:
glTexEnv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND)
Sets the current texture coordinates. Subsequent calls to glVertex*() result in those vertices being assigning the current texture coordinates.
glBegin(GL_QUAN) { glTexCoord2f (0, 0); glTexCoord2f (1, 0); glTexCoord2f (1, 1); glTexCoord2f (0, 1); } glVertex2f (0, 0, 5); glVertex2f (10, 0, 5); glVertex2f (10, 10, 5); glVertex2f (0, 10, 5);
Specifies the function for automatically generating texture coordinates. coord: GL_S, GL_T, GL_R, GL_Q
Recall Aliasing
Aliasing manifests itself as jaggies in graphics. Thus we dont have enough pixels to accurately represent the underlying function. Three reasons
Pixel numbers are fixed in the frame buffer Pixel locations are fixed on a uniform Pixel size/shape are fixed
Mip Mapping
MIP - multium in parvo - many in a small place. Build a pyramid of images, each smaller and filtered from the original.
Mipmapping
Thus as we render, we choose the texture that best fits what you are drawing. OpenGL supports mipmapping
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE, image); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
Bump Mapping
We can also use textures for so much more than just images! We can use the textures as a road map on how to perturb normals across a surface. As we shade each pixel, perturb the normal by the partial derivatives of the corresponding s, t in the bump map.
Environmental Mapping
Highly reflective surface are characterized by specular reflections that mirror the environment. We can extend our mapping techniques to obtain an image that approximates the desired reflection by extending texture maps to environmental (reflection) maps.
Environmental Mapping
Two-pass texture mapping
(1) Map the texture to a 3D intermediate surface. (2) Map the intermediate surface to the surface being rendered.
Object in environment Intermediate surface Projected object
Environmental Mapping
Then, we need to map the texture values on the intermediate surface to the desired surface.
n n n