Professional Documents
Culture Documents
An Interactive Introduction To Opengl Programming
An Interactive Introduction To Opengl Programming
OpenGL Programming
Dave Shreiner
Ed Angel
Vicki Shreiner
What Youll See Today
2
Goals for Today
3
OpenGL and GLUT Overview
Vicki Shreiner
OpenGL and GLUT Overview
5
What Is OpenGL?
6
OpenGL Architecture
Per Vertex
Polynomial Operations &
Evaluator Primitive
Assembly
Texture
Memory
Pixel
Operations
7
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.
8
Related APIs
application program
OpenGL Motif
widget or similar GLUT
GLX, AGL
or WGL GLU
1
0
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.
1
1
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
1
2
Sample Program
glEnable( GL_LIGHT0 );
glEnable( GL_LIGHTING );
glEnable( GL_DEPTH_TEST );
}
1
4
GLUT Callback Functions
1
5
Rendering Callback
1
7
User Input Callbacks
Vicki Shreiner
Elementary Rendering
Geometric Primitives
Managing OpenGL State
OpenGL Buffers
2
0
OpenGL Geometric Primitives
GL_TRIANGLES
GL_QUADS
GL_QUAD_STRIP
GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
2
1
Simple Example
void
void drawRhombus(
drawRhombus( GLfloat
GLfloat color[]
color[] ))
{{
glBegin(
glBegin( GL_QUADS
GL_QUADS );
);
glColor3fv(
glColor3fv( color
color );
);
glVertex2f(
glVertex2f( 0.0,
0.0, 0.0
0.0 );
);
glVertex2f(
glVertex2f( 1.0,
1.0, 0.0
0.0 );
);
glVertex2f(
glVertex2f( 1.5,
1.5, 1.118
1.118 );
);
glVertex2f(
glVertex2f( 0.5,
0.5, 1.118
1.118 );
);
glEnd();
glEnd();
}}
2
2
OpenGL Command Formats
glVertex3fv( v )
2
3
Specifying Geometric Primitives
Models
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
RGBA mode
2
5
Shapes Tutorial
2
6
Controlling Rendering
Appearance
From Wireframe to Texture Mapped
2
7
OpenGLs State Machine
2
8
Manipulating OpenGL State
Setting State
glPointSize(
glPointSize( size
size );
);
glLineStipple(
glLineStipple( repeat,
repeat, pattern
pattern );
);
glShadeModel(
glShadeModel( GL_SMOOTH
GL_SMOOTH );
);
Enabling Features
glEnable(
glEnable( GL_LIGHTING
GL_LIGHTING );
);
glDisable(
glDisable( GL_TEXTURE_2D
GL_TEXTURE_2D );
);
3
0
Transformations
Ed Angel
Transformations in OpenGL
Modeling
Viewing
orient camera
projection
Animation
Map to screen
3
2
Camera Analogy
camera
model
tripod
3
3
Camera Analogy and
Transformations
Projection transformations
adjust the lens of the camera
Viewing transformations
tripoddefine position and orientation of the viewing
volume in the world
Modeling transformations
moving the model
Viewport transformations
enlarge or reduce the physical photograph
3
4
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)
3
5
Affine Transformations
3
6
Homogeneous Coordinates
w is usually 1.0
all operations are matrix multiplications
directions (directed line segments) can be represented
3 with w = 0.0
7
3D Transformations
3
9
Programming Transformations
4
0
Transformation Poly.
Poly.
Per
Per
Vertex
Vertex
CPU DL Raster Frag FB
Pipeline
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
4
1
Matrix Operations
Specify
Specify Current
Current Matrix
Matrix Stack
Stack
glMatrixMode(
glMatrixMode( GL_MODELVIEW
GL_MODELVIEW or
or GL_PROJECTION
GL_PROJECTION ))
Other
Other Matrix
Matrix or
or Stack
Stack Operations
Operations
glLoadIdentity()
glLoadIdentity() glPushMatrix()
glPushMatrix()
glPopMatrix()
glPopMatrix()
Viewport
Viewport
usually
usually same
same as
as window
window size
size
viewport
viewport aspect
aspect ratio
ratio should
should be
be same
same as
as projection
projection
transformation
transformation or
or resulting
resulting image
image may
may be
be distorted
distorted
glViewport(
glViewport( x,
x, y,
y, width,
width, height
height ))
4
2
Projection Transformation
4
3
Applying Projection
Transformations
Typical use (orthographic projection)
glMatrixMode(
glMatrixMode( GL_PROJECTION
GL_PROJECTION );
);
glLoadIdentity();
glLoadIdentity();
glOrtho(
glOrtho( left,
left, right,
right, bottom,
bottom, top,
top, zNear,
zNear, zFar
zFar );
);
4
4
Viewing Transformations
4
6
Modeling Transformations
Move object
glTranslate{fd}( x, y, z )
Rotate object around arbitrary axis x y z
glRotate{fd}( angle, x, y, z )
angle is in degrees
Dilate (stretch or shrink) or mirror object
glScale{fd}( x, y, z )
4
7
Transformation Tutorial
4
8
Connection: 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
gluLookAt() has its own command
can make your own polar view or pilot view
4
9
Projection is left handed
3 examples of resize()
resize() routine
restate
restate projection
projection &
& viewing
viewing transformations
transformations
Usually called when window resized
Registered as callback for glutReshapeFunc
glutReshapeFunc()
()
5
1
resize(): Perspective &
LookAt
void
void resize(
resize( int
int w,
w, int
int hh ))
{{
glViewport(
glViewport( 0,
0, 0,
0, (GLsizei)
(GLsizei) w, w, (GLsizei)
(GLsizei) hh );
);
glMatrixMode(
glMatrixMode( GL_PROJECTION
GL_PROJECTION ); );
glLoadIdentity();
glLoadIdentity();
gluPerspective(
gluPerspective( 65.0,
65.0, (GLfloat)
(GLfloat) ww // h,
h,
1.0,
1.0, 100.0
100.0 ););
glMatrixMode(
glMatrixMode( GL_MODELVIEW
GL_MODELVIEW ); );
glLoadIdentity();
glLoadIdentity();
gluLookAt(
gluLookAt( 0.0,
0.0, 0.0,
0.0, 5.0,
5.0,
0.0,
0.0, 0.0,
0.0, 0.0,
0.0,
0.0,
0.0, 1.0,
1.0, 0.0
0.0 );
);
}}
5
2
resize(): Perspective &
Translate
Same effect as previous LookAt
void
void resize(
resize( int
int w,
w, int
int hh ))
{{
glViewport(
glViewport( 0,
0, 0,
0, (GLsizei)
(GLsizei) w, w, (GLsizei)
(GLsizei) hh );
);
glMatrixMode(
glMatrixMode( GL_PROJECTION
GL_PROJECTION ); );
glLoadIdentity();
glLoadIdentity();
gluPerspective(
gluPerspective( 65.0,
65.0, (GLfloat)
(GLfloat) w/h,w/h,
1.0,
1.0, 100.0
100.0 ););
glMatrixMode(
glMatrixMode( GL_MODELVIEW
GL_MODELVIEW ); );
glLoadIdentity();
glLoadIdentity();
glTranslatef(
glTranslatef( 0.0,
0.0, 0.0,
0.0, -5.0
-5.0 );
);
}}
5
3
resize(): Ortho (part 1)
void
void resize(
resize( int
int width,
width, int
int height
height ))
{{
GLdouble
GLdouble aspect
aspect == (GLdouble)
(GLdouble) width
width // height;
height;
GLdouble
GLdouble left
left == -2.5,
-2.5, right
right == 2.5;
2.5;
GLdouble
GLdouble bottom
bottom == -2.5,
-2.5, top
top == 2.5;
2.5;
glViewport(
glViewport( 0,
0, 0,
0, (GLsizei)
(GLsizei) w,w, (GLsizei)
(GLsizei) hh );
);
glMatrixMode(
glMatrixMode( GL_PROJECTION
GL_PROJECTION ););
glLoadIdentity();
glLoadIdentity();
continued
continued
5
4
resize(): Ortho (part 2)
5
5
Compositing Modeling
Transformations
Problem 1: hierarchical objects
one position depends upon a previous position
robot arm or hand; sub-assemblies
Solution 1: moving local coordinate
system
modeling transformations move coordinate system
post-multiply column-major matrices
OpenGL post-multiplies matrices
5
6
Compositing Modeling
Transformations
Problem 2: objects move relative to absolute
world origin
my object rotates around the wrong origin
make it spin around its center or something else
Solution 2: fixed coordinate system
modeling transformations move objects around fixed
coordinate system
pre-multiply column-major matrices
OpenGL post-multiplies matrices
must reverse order of operations to achieve desired effect
5
7
Additional Clipping Planes
5
8
Reversing Coordinate
Projection
Screen space back to world space
glGetIntegerv( GL_VIEWPORT, GLint viewport[4] )
glGetDoublev( GL_MODELVIEW_MATRIX, GLdouble mvmatrix[16] )
glGetDoublev( GL_PROJECTION_MATRIX,
GLdouble projmatrix[16] )
gluUnProject( GLdouble winx, winy, winz,
mvmatrix[16], projmatrix[16],
GLint viewport[4],
GLdouble *objx, *objy, *objz )
5
9
Animation and Depth Buffering
Vicki Shreiner
Animation and Depth Buffering
6
1
Double Poly.
Poly.
Per
Per
Vertex
Vertex
CPU DL Raster Frag FB
Buffering
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
1 1
2 2
4 4
Front 8 8 Back
16 16
Buffer Buffer
Display
6
2
Animation Using Double
Buffering
Request a double buffered color buffer
glutInitDisplayMode(
glutInitDisplayMode( GLUT_RGB
GLUT_RGB ||
GLUT_DOUBLE
GLUT_DOUBLE );
);
Clear color buffer
glClear(
glClear( GL_COLOR_BUFFER_BIT
GL_COLOR_BUFFER_BIT );
);
Render scene
Request swap of front and back buffers
glutSwapBuffers();
glutSwapBuffers();
Repeat steps 2 - 4 for animation
6
3
Depth Buffering and
Hidden Surface Removal
1 1
2 2
4 4
Color 8 8 Depth
16 16
Buffer Buffer
Display
6
4
Depth Buffering Using OpenGL
void
void main(
main( int
int argc,
argc, char**
char** argv
argv ))
{{
glutInit(
glutInit( &argc,
&argc, argv
argv );
);
glutInitDisplayMode(
glutInitDisplayMode( GLUT_RGB
GLUT_RGB ||
GLUT_DOUBLE
GLUT_DOUBLE || GLUT_DEPTH
GLUT_DEPTH ););
glutCreateWindow(
glutCreateWindow( Tetrahedron
Tetrahedron ););
init();
init();
glutIdleFunc(
glutIdleFunc( idle
idle );
);
glutDisplayFunc(
glutDisplayFunc( display
display );
);
glutMainLoop();
glutMainLoop();
6
6 }}
An Updated Program Template
(cont.)
void
void init(
init( void
void ))
{{
glClearColor(
glClearColor( 0.0,
0.0, 0.0,
0.0, 1.0,
1.0, 1.0
1.0 );
);
}}
void
void idle(
idle( void
void ))
{{
glutPostRedisplay();
glutPostRedisplay();
}}
6
7
An Updated Program Template
(cont.)
void
void drawScene(
drawScene( void
void ))
{{
GLfloat
GLfloat vertices[]
vertices[] == {{ };
};
GLfloat
GLfloat colors[]
colors[] == {{ };
};
glClear(
glClear( GL_COLOR_BUFFER_BIT
GL_COLOR_BUFFER_BIT ||
GL_DEPTH_BUFFER_BIT
GL_DEPTH_BUFFER_BIT ); );
glBegin(
glBegin( GL_TRIANGLE_STRIP
GL_TRIANGLE_STRIP ); );
/*
/* calls
calls to
to glColor*()
glColor*() and
and glVertex*()
glVertex*() */
*/
glEnd();
glEnd();
glutSwapBuffers();
glutSwapBuffers();
}}
6
8
Lighting
Dave Shreiner
Lighting Principles
7
1
Surface Poly.
Poly.
Per
Per
Vertex
Vertex
CPU DL Raster Frag FB
Normals
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
7
2
Material Properties
7
3
Light Properties
7
4
Light Sources (cont.)
7
5
Types of Lights
7
6
Turning on the Lights
7
7
Light Material Tutorial
7
8
Controlling a Lights Position
7
9
Light Position Tutorial
8
0
Advanced Lighting Features
Spotlights
localize lighting affects
GL_SPOT_DIRECTION
GL_SPOT_CUTOFF
GL_SPOT_EXPONENT
8
1
Advanced Lighting Features
Light attenuation
decrease light intensity with distance
GL_CONSTANT_ATTENUATION
GL_LINEAR_ATTENUATION
GL_QUADRATIC_ATTENUATION
1
fi
k c kl d k q d 2
8
2
Light Model Properties
8
4
Imaging and Raster Primitives
Vicki Shreiner
Imaging and Raster Primitives
8
6
Pixel-based primitives
Bitmaps
2D array of bit masks for pixels
update pixel color based on current color
Images
2D array of pixel color information
complete color information for each pixel
OpenGL doesnt understand image
formats
8
7
Per
Poly. Per
Poly. Vertex
Pixel Pipeline
Vertex
CPU DL Raster Frag FB
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
TextureM glCopyTex*Image();
emory
glReadPixels(), glCopyPixels()
Positioning Image Primitives
glRasterPos3f( x, y, z )
raster position transformed like geometry
discarded if raster position is
outside of viewport
may need to fine tune
viewport for desired results
Raster Position
8
9
Rendering Bitmaps
height
xmove ymove
yorig
width
xorig
xmove
9
0
Rendering Fonts using Bitmaps
9
1
Rendering Images
9
2
Reading Pixels
9
3
Pixel Zoom
glPixelZoom( x, y )
expand,
expand, shrink
shrink or
or reflect
reflect pixels
pixels
around
around current
current raster
raster position
position
fractional
fractional zoom
zoom supported
supported
Raster glPixelZoom(1.0, -1.0);
Position
9
4
Storage and Transfer Modes
9
5
Texture Mapping
Ed Angel
Texture Poly.
Poly.
Per
Per
Vertex
Vertex
CPU DL Raster Frag FB
Mapping
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
9
7
Texture Mapping
z x
geometry screen
t
image
9
8
s
Texture Mapping and the
OpenGL Pipeline
Images and geometry flow through
separate pipelines that join at the
rasterizer
complex textures do not affect geometric
complexity
1
0
Applying Textures I
Three steps
specify texture
read or generate image
assign to texture
assign texture coordinates to vertices
specify texture parameters
wrapping, filtering
1
0
Applying Textures II
specify
specify textures
textures inin texture
texture objects
objects
set
set texture
texture filter
filter
set
set texture
texture function
function
set
set texture
texture wrap
wrap mode
mode
set
set optional
optional perspective
perspective correction
correction hint
hint
bind
bind texture
texture object
object
enable
enable texturing
texturing
supply
supply texture
texture coordinates
coordinates for
for vertex
vertex
coordinates
coordinates can
can also
also be
be generated
generated
1
0
Texture Objects
1
0
Texture Objects (cont.)
1
0
Specify Texture Poly.
Poly.
Per
Per
Vertex
Vertex
CPU DL Raster Frag FB
Image
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
1
0
Specifying a Texture:
Other Methods
Use frame buffer as source of texture image
uses current buffer as source image
glCopyTexImage2D(...)
glCopyTexImage1D(...)
Modify part of a defined texture
glTexSubImage2D(...)
glTexSubImage1D(...)
Do both with glCopyTexSubImage2D(...), etc.
1
0
Mapping a Poly.
Poly.
Per
Per
Vertex
Vertex
CPU DL Raster Frag FB
Texture
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
c (0.4, 0.2)
b
B C
0, 0 1, 0 s (0.8, 0.4)
1
0
Generating Texture Coordinates
1
1
Texture Application Methods
Filter Modes
minification or magnification
special mipmap minification filters
Wrap Modes
clamping or repeating
Texture Functions
how to mix primitives color with textures color
blend, modulate or replace texels
1
1
Filter Modes
Example:
glTexParameteri( target, type, mode );
Example:
glTexParameteri( GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP )
glTexParameteri( GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_REPEAT )
s
GL_REPEAT GL_CLAMP
texture
wrapping wrapping
1
1
Texture Functions
1
1
Perspective Correction Hint
1
1
Texture Residency
1
1
Advanced OpenGL Topics
Dave Shreiner
Advanced OpenGL Topics
1
2
Immediate Mode versus Display
Listed Rendering
Immediate Mode Graphics
Primitives are sent to pipeline and display right away
No memory of graphical entities
Display Listed Graphics
Primitives placed in display lists
Display lists kept on graphics server
Can be redisplayed with different state
Can be shared among OpenGL graphics contexts
1
2
Immediate Mode versus
Display Lists
Immediate Mode
Per Vertex
Polynomial Operations &
Evaluator Primitive
Assembly
Display Listed
Texture
Memory
Pixel
Operations
1
2
Per
Poly. Per
Poly. Vertex
Display Lists
Vertex
CPU DL Raster Frag FB
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
1
2
Advanced Primitives
Vertex Arrays
Bernstein Polynomial Evaluators
basis
basis for
for GLU
GLU NURBS
NURBS
NURBS
NURBS (Non-Uniform
(Non-Uniform Rational
Rational B-Splines)
B-Splines)
GLU Quadric Objects
sphere
sphere
cylinder
cylinder (or
(or cone)
cone)
disk
disk (circle)
(circle)
1
2
Vertex Poly.
Poly.
Per
Per
Vertex
Vertex
CPU DL Raster Frag FB
Arrays
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
1
2
Why use Display Lists or Vertex
Arrays?
May provide better performance than
immediate mode rendering
Display lists can be shared between
multiple OpenGL context
reduce memory usage for multi-context applications
Vertex arrays may format data for better
memory access
1
2
Alpha: the 4th Color Component
Measure of Opacity
simulate translucent objects
glass, water, etc.
composite images
antialiasing
ignored if blending is not enabled
glEnable( GL_BLEND )
1
2
Per
Poly. Per
Poly. Vertex
Blending
Vertex
CPU DL Raster Frag FB
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
Example of bump-mapping
done with a multi-pass
OpenGL algorithm
1
3
Antialiasing
1
3
Accumulation Buffer
1
3
Accessing Accumulation Buffer
1
3
Accumulation Buffer
Applications
Compositing
Full Scene Antialiasing
Depth of Field
Filtering
Motion Blur
1
3
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 out
these artifacts
1
3
Depth of Focus : Keeping a
Plane in Focus
Jitter the viewer to keep one plane
unchanged Back Plane
Focal Plane
Front Plane
1
3
Fog Tutorial
1
3
Feedback Mode
1
4
Selection Mode
1
4
Selection Mode (cont.)
1
4
Picking
1
4
Picking Template
glutMouseFunc( pickMe );
1
4
Picking Template (cont.)
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
gluPickMatrix( (GLdouble) x, (GLdouble)
(myViewport[3]-y), 5.0, 5.0, myViewport );
/* gluPerspective or glOrtho or other projection */
glPushName( 1 );
/* draw something */
glLoadName( 2 );
/* draw something else continue */
1
4
Picking Template (cont.)
glMatrixMode( GL_PROJECTION );
glPopMatrix();
hits = glRenderMode( GL_RENDER );
/* process nameBuffer */
}
1
4
Picking Ideas
Scissor
Scissor Alpha
Alpha Stencil
Stencil
Test
Test Test
Test Test
Test
Framebuffer
Depth
Depth Logical
Logical
Blending
Blending Dithering
Dithering
Test
Test Operations
Operations
1
4
Scissor Box
1
4
Per
Poly. Per
Poly. Vertex
Alpha Test
Vertex
CPU DL Raster Frag FB
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
1
5
Per
Poly. Per
Poly. Vertex
Stencil Buffer
Vertex
CPU DL Raster Frag FB
CPU DL Raster Frag FB
Texture
Texture
Pixel
Pixel
1
5
Controlling Stencil Buffer
1
5
Creating a Mask
glInitDisplayMode( |GLUT_STENCIL| );
glEnable( GL_STENCIL_TEST );
glClearStencil( 0x1 );
1
5
Using Stencil Mask
1
5
Dithering
glEnable( GL_DITHER )
Dither colors for better looking results
Used to simulate more available colors
1
5
Logical Operations on Pixels
1
5
Advanced Imaging
Imaging Subset
Only available if GL_ARB_imaging defined
Color matrix
Convolutions
Color tables
Histogram
MinMax
Advanced Blending
1
5
Summary / Q & A
Dave Shreiner
Ed Angel
Vicki Shreiner
On-Line Resources
http://www.opengl.org
start here; up to date specification and lots of sample code
news:comp.graphics.api.opengl
http://www.sgi.com/software/opengl
http://www.mesa3d.org/
Brian Pauls Mesa 3D
http://www.cs.utah.edu/~narobins/opengl.html
very special thanks to Nate Robins for the OpenGL Tutors
source code for tutors available here!
1
5
Books
1
6
Thanks for Coming
1
6