Part 1

advertisement
Introduction to OpenGL
(part 1)
Ref: OpenGL Programming Guide
(The Red Book)
Fall 2009 revised
1
Topics
Part 2
Part 1




Introduction
Geometry
Viewing and
Rendering Pipeline
Light & Material



Display List
Alpha Channel
Polygon Offset
Part 3


Image
Texture Mapping
Part 4


Fall 2009 revised
Framebuffers
Selection & Feedback
2
OPEN GL
Introduction
Fall 2009 revised
3
Introduction
2D/3D graphics API created by SGI
(1992)

250 function calls in C
Cross platform: MacOS, Windows, Linux,
Unix, Playstation 3
Specifications controlled by OpenGL
ARB (architecture review board)
Currently (as of Aug 2007): OpenGL 2.1
Aug 2011: OpenGL 4.1
Fall 2009 revised
Version Query
4
Client-Server Execution Model
client

The application program issuing graphic commands
server


OpenGL that interprets and displays
Can be the same or other computers over the network
Client
An application issuing
graphics commands
SERVER
Interpret and process commands;
Maintain graphics contexts
Fall 2009 revised
5
OpenGL Related APIs
GLUT (toolkit)
GLU (utility)


part of OpenGL
implementation
useful groupings of
OpenGL commands





window management
handling input events
drawing 3-D primitives
managing background
(idle) process
running program (main
loop)
Interface Codes

Fall 2009 revised
PUI, MUI, GLUI, …
6
OpenGL and Related APIs
application program
OpenGL Motif
widget or similar
GLUT
GLX, AGL
or WGL
GLU
X, Win32, Mac O/S
GL
software and/or hardware
Fall 2009 revised
7
OpenGL on VC6
File/New as Win32
console application
GLUT Installation



glut32.dll in
Windows/System
glut32.lib in lib/
glut.h in include/GL
Fall 2009 revised
8
VC7 : Visual Studio .NET 2003
VC7 with glut (ref)
Fall 2009 revised
9
VC9 : Visual Studio 2008
VC9 with glut (ref)
Fall 2009 revised
10
GLUT for Win32
This is what you need to run
This contains a lot of example codes,
from simple to sophisticated
Fall 2009 revised
11
Online Resources
API references

(1)
Redbook

Ver 1.1 (HTML)
Tutorials

(see course homepage)
Fall 2009 revised
12
Example 1: double.c
Study objectives:





Compiling OpenGL program
Basics of double-buffered animation
The order the subroutines execute
Concept of state variables (glColor)
Commands:
 Glut basics
 glClear
 glFlush:force all previous issued commands to begin execution; required for single
buffered application
Fall 2009 revised
13
Double-Buffered Animation
Fall 2009 revised
14
Ex: double.c
void reshape(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
static GLfloat spin = 0.0;
glLoadIdentity();
glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);
void display(void)
glMatrixMode(GL_MODELVIEW);
{
glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity();
}
glPushMatrix();
void mouse(int button, int state, int x, int y)
glRotatef(spin, 0.0, 0.0, 1.0);
{
glColor3f(1.0, 1.0, 1.0);
switch (button) {
glRectf(-25.0, -25.0, 25.0, 25.0);
case GLUT_LEFT_BUTTON:
glPopMatrix();
if (state == GLUT_DOWN)
glutIdleFunc(spinDisplay);
glutSwapBuffers();
break;
}
case GLUT_MIDDLE_BUTTON:
case GLUT_RIGHT_BUTTON:
void spinDisplay(void)
if (state == GLUT_DOWN)
{
glutIdleFunc(NULL);
spin = spin + 2.0;
break;
if (spin > 360.0)
default:
spin = spin - 360.0;
break;
glutPostRedisplay();
}
}
}
Fall 2009 revised
#include <GL/glut.h>
#include <stdlib.h>
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode
(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (250, 250);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
15
Additional Topics
Time a function
Frame rate (FPS) computation
Time-based animation
Fall 2009 revised
16
OPEN GL
Geometry
Fall 2009 revised
17
OpenGL Geometry Primitives
Fall 2009 revised
18
Defining Primitives
Each primitive


Bounded by glBegin and glEnd
Defined by the following commands:
 Vertex location (glVertex): local (object)
coordinates
 Most other OpenGL commands are for statespecification: (normal, color, texture
coordinates, etc.)
Fall 2009 revised
19
Examples
Commands between Begin and End


Allowable OpenGL commands (next page); others
are not allowable
non-OpenGL commands are not restricted
Fall 2009 revised
20
Valid Commands Between
glBegin & glEnd
Fall 2009 revised
21
Restrictions on polygons
simple (no self intersection)
planar: no guarantee of correct
rendering for nonplanar “polygons”
convex
no holes
Examples of illegal polygons
Fall 2009 revised
22
Drawing Styles
glPointSize (GLfloat)
glLineWidth (GLfloat)
glLineStipple (factor,
pattern)

Advanced use of line
stipple for neon signs
Fall 2009 revised
23
Drawing Styles (cont)
glPolygonMode
Related:


1
glFrontFace: specifies
whether polygons with CW
winding, or CCW winding, in
window coordinates, are
taken to be front-facing
glCullFace: specifies
whether front- or backfacing facets are candidates
for culling
4
F
2
3
glFrontFace (GL_CCW);
[stippled polygon: a
simple “texture”]
Fall 2009 revised
24
Concave Polygons
Break concave ones into convex pieces


Manually doing so (as shown next page)
GLU has utility for tessellation !
 [we’ll do so after displaylist]
Use glEdgeFlag () to outline polygons
Fall 2009 revised
25
glEdgeFlag (Glboolean flag)
Indicates whether a vertex should be considered as
initializing a boundary edge of a polygon. If flag of a
vertex is set GL_TRUE (default), the vertices created
are considered to precede boundary edges until this
function is called again with flag being GL_FALSE.
Hence, v1v2 is
Fall 2009 revised
disabled
26
Example of glEdgeFlag
v1:(-20,20)
V4:(-10,-10)
V2:(-20,-20)
V3:(20,-20)
Use the same code;
change display style
only!
Fall 2009 revised
27
[More on
TRIANGLE|QUAD_STRIP]
Faces constructed (note: consistent CW/CCW)



Winding according to first face
(v0,v1,v2), (v2,v1,v3),(v2,v3,v4),…
(v0,v1,v3,v2),(v2,v3,v5,v4),(v4,v5,v6,v7)
Normal assignment


Per vertex: as before
Per face: set at strip vertex (the last
defining vertex of the face)
Stripification: make strips out of
triangular mesh (ref)
Fall 2009 revised
28
Ex: drawing icosahedron
Setting normal vectors
normal convention:
outward-pointing unit
vectors
 should always supply
normalized vectors
Related call:
glEnable (GL_NORMALIZE);

 enabling system to
normalize normal
vectors after transforms
Geometry construction:
avoid T-section
HSR (hidden surface
removal) with z-buffer
(depth buffer)
Scale esp.
Fall 2009 revised
29
Without glEnable (GL_NORMALIZE)
Original size
glScalef(.3,.3,.3);
glScalef(3,3,3);
n  M T n
 1s



n  S T n   1s
n
1

s
Diffuse intensity  n·l
Fall 2009 revised
30
Primitives in GLUT
Platonic Solids
Other Solids
Sphere
Cone
Cube
(Utah) Teapot
Fall 2009 revised
31
Glut Primitives (Torus)
Depth Buffer Related Functions
glClear (GL_DEPTH_BIT)

set all pixels to the largest possible distance (default: 1.0)
glClearDepth (1.0) --- default


Depth range: [zNear, zFar]  [0.0, 1.0]
1.0: set depth to zFar
glDepthFunc:


(fragment) pass the test if its z value has the specified
relationship to the value already in the depth buffer
default: GL_LESS
glEnable (GL_DEPTH_TEST)
More on Chap 10 (Framebuffers)
Fall 2009 revised
33
Vertex Arrays
The default way to specify
geometry in OpenGL-ES
Boost efficiency by


Reducing number of API calls
Reducing repetitive processing on shared vertices
Three steps of using VA:

Enable arrays
 glEnableClientState/glDisableClientState

Specify data for the arrays
 glVertexPointer

Dereference and rendering
 glArrayElement(i)
 glDrawElements(mode, count, type, indices)
 glArrayElements(mode, first, count)
Fall 2009 revised
34
Vertex Array (cont)
Enabling and Setting
Dereferencing
Fall 2009 revised
35
Vertex Array (cont)
Fall 2009 revised
36
From the Spec
Fall 2009 revised
37
The data of vertex array are stored on
client side
glEnableClientState
GL_COLOR_ARRAY,
GL_EDGE_FLAG_ARRAY,
GL_INDEX_ARRAY,
GL_NORMAL_ARRAY,
GL_TEXTURE_COORD_ARRAY, and
GL_VERTEX_ARRAY are accepted.
Fall 2009 revised
38
CG Primer
Rendering
Light-material interaction
Hidden surface removal and Z-buffer
Fall 2009 revised
39
OPEN GL
Viewing
Fall 2009 revised
40
VIEWING
The camera analogy




Modeling
Viewing
Projection
Viewport
Fall 2009 revised
41
Rendering Pipeline Tutorial
No longer on line [local copy]
Fall 2009 revised
42
Rendering Pipeline (Foley and van Dam)
Fall 2009 revised
43
Rendering Pipeline (OpenGL)
stages of vertex transform
Fall 2009 revised
44
Two Transformation Matrices
ModelView: geometry transformation
and viewpoint placement (dual)
Projection: orthographic and
perspective
Fall 2009 revised
45
Modeling Transformation
Transform object coords
to world coords
modeling
transformations:




Example

order of interpretation:
INML v
glTranslate
glRotate
glScale
glMultMatrix
each command
generates a 4x4 matrix
the current matrix (the
one on top of stack) is
then post-multiplied by
the transform
Fall 2009 revised
46
Hence, ...
glRotate (30, 0, 0, 1);
glTranslate (10, 0, 0);
drawPlant( );
glTranslate (10, 0, 0);
glRotate (30, 0, 0, 1);
drawPlant( );
Fall 2009 revised
47
Alternate Perspective of
Modeling Transformation
Instead of thinking in terms of the
global, fixed coordinate axes, consider
the local axes.

revisit previous page!
for articulated robot arms, this local
view is more straightforward
Transformation involving scaling
A three-page CAD article (1995) by
Lee and Koh talked about this
Fall 2009 revised
48
Viewing Transform
glTranslate (0, 0, -5)
Transform world
coords to eye coords
Dual of modeling
transformation
Fall 2009 revised
49
Viewing Transform (cont)
two ways to do so:

use glTranslate & glRotate
 less confusing if think in terms of moving objects)

gluLookAt (pos, at, up)
 pos, at: points in world coord.
 up: vector in world coord.
default camera


position at origin
pointed to negative-z
DETAIL
Fall 2009 revised
50
Viewing Transform (cont)
Typically, issue view transformation
commands BEFORE any modeling
transformation

Follow the general convention of rendering
pipeline:
 first commands interpreted last (global view)
Fall 2009 revised
51
Projection Transformation
Idea:

3D eye coords(clip & project)  2D
device coords
Fall 2009 revised
52
Viewing Volumes: Ortho and Perspective
glOrtho:

Watch out for zfar and znear
Specify the distances to the nearer and farther depth clipping planes.
These distances are negative if the plane is to be behind the viewer.
gluOrtho2D (special version for xy plots)
In eye
coords.
Fall 2009 revised
53
Viewing Volumes (cont)
glFrustum
gluPerspective



symmetry viewing volume guaranteed
zNear and zFar are always positive in these cases
zNear must never be zero
[fovx=fovy*aspect]
Fall 2009 revised
54
Precision Issues in Setting zNear & zFar
From the Spec.
Fall 2009 revised
55
Symptoms
The “aliasing” comes from z-fighting
(disappear when culling is ON).
The result of setting small
zNear (0.1, 0.001)
Fall 2009 revised
56
Math of Perspective Projection
Fall 2009 revised
57
Viewport Transformation
How the rendered content is to be drawn on
screen

Location, aspect ratio control
Fall 2009 revised
58
Applications of Viewports
Multi-viewport display


TV walls
Game: 3D, compass; 1st and 3rd person
views
Viewport animation

Growing/shrinking views
Fall 2009 revised
59
Summary of OpenGL Pipeline
Fall 2009 revised
60
Commands for Matrix Manipulation
glLoadIdentity
glLoadMatrix: replace current matrix (CM)
glMultMatrix: post-multiply CM

Matrix declared as m[16]
glGetFloatv
(GL_MODELVIEW_MATRIX,m):
Fall 2009 revised
get CM
61
#include <GL/glut.h>
#include <stdlib.h>
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glLoadIdentity ();
/* clear the matrix */
/* viewing transformation */
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glScalef (1.0, 2.0, 1.0); /* modeling transformation */
glutWireCube (1.0);
glFlush ();
}
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
glMatrixMode (GL_MODELVIEW);
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
Fall 2009 revised
62
Matrix Stacks
Display multiple objects, each with a different
modeling transform
Philosophy:

Instead of having various matrices, only provide
one matrix for modelview (to save resources)
 One other matrix available for projection; Use
glMatrixMode to select the one to operate on

Use glPopMatrix and glPushMatrix for stack
manipulation
Fall 2009 revised
63
Object Placement using Push/Pop
PushMatrix
Translate (8,5)
draw
PopMatrix
(3,9)
(8,5)
PushMatrix
Translate (3,9)
draw
PopMatrix
Draw tree at default pos
Fall 2009 revised
64
Matrix Stacks (cont)
Simply put,

glPushMatrix
 topmost is duplicated

glPopMatrix
 Remove the top one
useful for constructing
hierarchical/articulated
models
examples: solar system
[planet.c]
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glPushMatrix();
glutWireSphere(1.0, 20, 16); /* draw sun */
glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (2.0, 0.0, 0.0);
glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.2, 10, 8); /* draw smaller planet */
glPopMatrix();
glutSwapBuffers();
Fall 2009 revised
65
}
Articulated Object
q3
q2
q1
Link at default pos
Fall 2009 revised
Link1:
Rotate(z,q1);
draw
Link2:
Rotate(z,q1);
Translate(h,0,0)
Rotate(z,q2);
draw
Link3:
Rotate(z,q1);
Translate(h,0,0)
Rotate(z,q2);
Translate(h,0,0)
Rotate(z,q3);
draw
66
Link1:
Rotate(z,q1)
draw
Link2:
Rotate(z,q1)
Translate(h,0,0)
Rotate(z,q2)
draw
Link3:
Rotate(z,q1)
Translate(h,0,0)
Rotate(z,q2)
Translate(h,0,0)
Rotate(z,q3)
draw
PushMatrix
Rotate(z,q1)
draw // link1
Translate(h,0,0)
Rotate(z,q2)
draw // link2
Translate(h,0,0)
Rotate(z,q3)
draw // link3
PopMatrix
Fall 2009 revised
67
Misc. Topics
Cutaway View: glClipPlane
Unproject: reverse transform
Debugging: glGetError
Transforming Normal Vectors
Transforming Plane Equations
Fall 2009 revised
68
OPEN GL
Colors
Fall 2009 revised
69
COLORS
Color Indexed vs. RGBA
Color Space: HSB
Fall 2009 revised
70
Colors (cont)
glGetIntegerv (GL_RED_BITS, GREEN,
BLUE, ALPHA)

number of bitplanes available on your
system
in general, use RGBA

works better with texture mapping, lighting,
shading, fog, anti-aliasing and blending
Fall 2009 revised
71
Back to OpenGL
glLightModel
Light Properties

Color:

 Ambient, diffuse,
specular

Position:
 nullity of w matters
 [homogeneous
coordinate]


attenuation coefficients;
spot light (cutoff,
direction)

use Modelview matrix to
change position/dir
Fall 2009 revised
global ambient light: the
"ambient" effect that is not
attributed to any particular
source
local or infinite viewpoint:
specular calculation; in
infinite viewer, view is -Z
two-sided lighting: may be
used for cutaway view;
backfaces are rendered
according to reversed
normal
72
Position of Light
Specified using glLightfv (GL_LIGHTx,
GL_POSITION, pos);
From API documentation:
The position is transformed by the modelview matrix when
glLight is called (just as if it were a point), and it is
stored in eye coordinates. If the w component of the
position is 0.0, the light is treated as a directional source.
Different kinds of light:


Stationary, moving, headlight (move with camera)
Different setting of matrix stack
Fall 2009 revised
73
Moving vs. Stationary Light
Stationary light
Head light
The position of the head light, in eye coord, remains the same
regardless of the camera position; whereas the position of the
stationary light, in eye coord, changes as camera moves.
Fall 2009 revised
74
Spotlight
From API documentation:
The spot direction is transformed by the
inverse of the modelview matrix when
glLight is called (just as if it were a
normal), and it is stored in eye coordinates.
It is significant only when
GL_SPOT_CUTOFF is not 180, which it is
by default. The default direction is (0,0,-1).
Fall 2009 revised
75
Material Specification in OpenGL
glMaterialfv (face, mode, Examples
value_ptr)
light.c, material.c, scene.c

Ambient, diffuse,
specular, emission

glColorMaterial (face,
mode); then use glColor

glEnable
(GL_COLOR_MATERIAL)
general guide
teapots.c

source for good parameters
movelight.c

on moving a positional light
colormat.c

using color material mode
Color material can be
more efficient, but
beware of the pitfall (ref)
Fall 2009 revised
76
ColorMaterial
Can be More Efficient
•
•
•
If you are rendering objects that require frequent simple material
changes, try to use the color material mode.
With color material enabled, material colors track the current color
always be careful to set glColorMaterial before you enable
GL_COLOR_MATERIAL
Fall 2009 revised
77
Push/Pop Attributes
glPushAttrib:
takes one argument, a mask that indicates
which groups of state variables to save on the attribute stack.
Symbolic constants are used to set bits in the mask. mask is
typically constructed by ORing several of these constants
together. The special mask GL_ALL_ATTRIB_BITS can be used
to save all stackable states.
Common used (See API doc for details)





GL_ENABLE_BIT (all disable/enable)
GL_CURRENT_BIT (current RGBA color)
GL_POLYGON_BIT (culling, polygonmode)
GL_TRANSFORM_BIT (matrixmode)
GL_TEXTURE_BIT (texture stuff)
Fall 2009 revised
78
End of Part 1
Fall 2009 revised
79
Frame Rate
FPS


frames per second: many how frames got
displayed in a second
1/(time required for single-frame display)
For a sufficiently smooth animation, fps > 24
To measure the time a display routine takes

Use QueryPerformanceCounter (next pages)
To periodically display FPS, use
glutTimerFunc()
Fall 2009 revised
BACK
80
Time a function
For low-precision timing, int glutGet
(GLUT_ELAPSED_TIME) is sufficieint [in msec]
Fall 2009 revised
81
Example
BACK
Fall 2009 revised
82
Time-based Animation
Assume the angular velocity of the object is 10RPM
(round-per-minute)
Make sure the object rotates in the same speed on
different machines
q
  lim
, q  t
t 0 t
Angular displacement
between frames
Elapsed time
between display
q  t
q (deg)  RPM
round
min
  360
1
60
min
sec
Fall 2009 revised
deg
round
t (sec)
BACK
83
Rendering
The computation required to
convert 3D scene to 2D display
photo-realistically
BACK
Fall 2009 revised
84
HSR (Hidden Surface Removal)
Painters algorithm



Depth-sorting; Back-to-front rendering
Sort based on some points on the polygon
Problem: can not resolve this:
Fall 2009 revised
85
HSR (cont)
Z-buffer Algorithm



For each pixel, we keep track of the corresponding depth or
distance.
This is called the z-buffer.
If a new object is drawn, only replace the pixels in the
frame-buffer if the new pixel’s value is less than the pixel’s
value in the z-buffer.
Fall 2009 revised
86
Z-Buffer
Note: OpenGL has 0 at the near end and
1 at the far end
Fall 2009 revised
87
OpenGL Related
OpenGL depth buffer value clamped to [0,1]

0 at near; 1 at far
glClearDepth();

Set depth clear value
glGetFloatv (GL_DEPTH_CLEAR_VALUE);

Query current depth clear value
glGetIntegerv (GL_DEPTH_BITS);

24 [for my platform]
glClear (GL_DEPTH_BUFFER_BIT);

Clear depth buffer
Fall 2009 revised
88
Z-buffer in OpenGL
MUST do these
three things for
Z-buffer to work!
BACK
Fall 2009 revised
89
Shading
the gradation (of
color) that give the
2D images the
appearance of being
3D
light-material
interaction
specular
Fall 2009 revised
diffuse
translucent
90
Light
point, spot,
directional lights
ambient light: to
account for uniform
level room lighting
describe a light
source through a
three-component
(RGB) intensity
Fall 2009 revised
91
Phong Reflection Model
Diffuse (漫射)
Specular
Fall 2009 revised
Ambient
92
Phong Reflection Model
L: light source property (RGB)
R: material property (RGB)
ambient reflection
diffuse reflection
To consider distance attenuation
specular reflection
a: shininess coefficient
final result
Fall 2009 revised
93
Phong Model (cont)
For multiple light sources:
Fall 2009 revised
94
Shading Modes
Flat vs. Smooth



Flat: single color per
face
Gouraud (intensity
interpolation)
Phong (normal
interpolation)
Local vs. Global
Fall 2009 revised
95
Gouraud vs. Phong
• Most h/w implement Gouraud shading
• Phong shading can better imitate specular
effects (∵normals are interpolated)
Fall 2009 revised
96
Compare: Flat, Gouraud, Phong
BACK
Fall 2009 revised
97
Ex: Involving Uniform Scaling
Translate(-3,-1)
Scale(2,2)
Translate(1,2)
Vertex(x,y)
 2   3
 1   5 
   
1  1
Fall 2009 revised
1


0
1
 
0
1
 
0
 3 2
0 1
1  1  2 0  1
0 1  0 0 1 0 0
 3 2
0  x  1 
1  1  2 0  y  2
0 1  0 0 1  1 
1  x 
2  y 
1   1 
 3  2( x  1) 
1  1 2( y  2)
0 1   1 
 2( x  1)  3 
 2( y  2)  1


1
98
Step-1
Translate(-3,-1)
Scale(2,2)
Translate(1,2)
Vertex(x,y)
Fall 2009 revised
99
Step-2
Translate(-3,-1)
Scale(2,2)
Translate(1,2)
Vertex(x,y)
Fall 2009 revised
100
Step-3
Translate(-3,-1)
Scale(2,2)
Translate(1,2)
Vertex(x,y)
Note:
translation
in new scale
Fall 2009 revised
101
Step-4
Translate(-3,-1)
Scale(2,2)
Translate(1,2)
Vertex(x,y)
 2   3
 1   5 
   
1  1
BACK
Fall 2009 revised
102
Projection: Ortho and Perspective
Fall 2009 revised
103
Math of Perspective Projection
Perspective Division
Fall 2009 revised
104
Perspective Projection (cont)
Expressed in homogeneous coordinates
BACK
Fall 2009 revised
105
Vectors and Points are Different!
Point
Homogenenous
coordinate
Vector
Homogeneous
coordinate
p = [x y z 1]
v = [x y z 0]
M: affine transform
(translate, rotate,
scaling, reflect, …)
p’= M p
(ref)
Affine transform
(applicable when M is
invertible (full rank;
projection to 2D is not)
v’= (M-1)T v
Fall 2009 revised
106
v’=Mv won’t work
non - uniformscaling M
0 
p1  1
1
1
p2  0
1
1
v  1
0
 2 0 0
 0 1 0
0 0 1
0 0  0  0 
1 0 1  1
0 1 1 1
2
p1  Mp1  0
0
2 0 0 1 2
p2  Mp2  0 1 0 0  0
0 0 1 1 1
2 0 0 1 2
v  Mv  0 1 0 1  1
0 0 1 0 0
Fall 2009 revised
107
On
(M-1)T
The w (homogeneous
coord) of vectors are 0;
hence, the translation
part (31 vector) plays
no role
For rotation, M-1=MT,
hence (MT)T = M: rotate
the vector as before
For scaling:


M 


0
sx

M 



 s1x

M 1  



Fall 2009 revised



0



0




1
sy
sz
1
sy
1
sz


v 

 
0 





1


  M T


1
108
Hence
non - uniformscaling M
 12
1
v  1 v  M T v  0
0
0
 2 0 0
 0 1 0
0 0 1
0 0 1  12 
1 0 1  1
0 1 0 0
This is known as the normal
matrix (ref)
BACK
Fall 2009 revised
109
Homogeneous Coordinate
[ x1 , x2 , x3 ]  [
x1 x2
, ,1]
x3 x3
BACK
Fall 2009 revised
110
Color Models
RGB:

CMY:
additive color

Fall 2009 revised
subtractive colors
111
Color Models (cont)
HSB:



Hue: defines the color; from Red-Green-Blue
Saturation: how the hue differs from natural grey
Brightness: the level of illumination
Fall 2009 revised
112
HSB to RGB
Can be useful in
setting color variation
in fireworks!
BACK
Fall 2009 revised
113
Pipeline Review
Modelview
Matrix
Model
Transform
Viewing
Transform
world
coordinates
Fall 2009 revised
114
OpenGL
minimal
Template
Pipeline related code inserted here…
Fall 2009 revised
115
Modelview
Matrix
Model
Transform
Viewing
Transform
world
coordinates
Open a viewport, the same
size as the window
Note: if the window is
reshaped, this needs to be
executed again (hence
usually given in reshape
callback)
Fall 2009 revised
116
Modelview
Matrix
Model
Transform
Viewing
Transform
world
coordinates
Set up the projection matrix [set
the camera characteristics]
Fall 2009 revised
117
Modelview
Matrix
Model
Transform
Viewing
Transform
world
coordinates
Set up viewing transform
[where the camera is]
y
x
z
Fall 2009 revised
118
Modelview
Matrix
Model
Transform
Viewing
Transform
world
coordinates
Set the model transform
Fall 2009 revised
119
Modelview
Matrix
Model
Transform
Viewing
Transform
world
coordinates
y
(0,1)
x
The geometry specified in
object (local) coordinates
Fall 2009 revised
120
Remarks on Setting Pipeline
Parameters
The order of specification (viewport,
projection, modelview) is irrelevant. As long
as they are set before geometric commands
(glBegin/glEnd) are sent through pipeline
If the setting is unchanged throughout the
program, it is common to move them to
reshape callback [no need to set them every
time]
[What should you do for viewport animation?!]
Fall 2009 revised
BACK
121
Cutaway View
glClipPlane (for displaying cutaway view
of an object)
watch out on how coefficients are set
(see API docs for more detail)
Fall 2009 revised
122
Advanced Clipping (ref)
With Stencil Buffer (later)
Fall 2009 revised
123
glClipPlane
Can one show x-section of object?
When glClipPlane is called, equation is
transformed by the inverse of the modelview
matrix and stored in the resulting eye
coordinates. Subsequent changes to the
modelview matrix have no effect on the
stored plane-equation components.
If the dot product of the eye coordinates of a
vertex with the stored plane equation
components is positive or zero, the vertex is
in with respect to that clipping plane.
Otherwise, it is out.
BACK
Fall 2009 revised
124
Transformation: gluProject
(object coords) (window coords)
glGetIntegerv (GL_VIEWPORT, viewport);
glGetDoublev (GL_MODELVIEW_MATRIX, mvmatrix);
glGetDoublev (GL_PROJECTION_MATRIX, projmatrix);
winx  wx, wx  w
winy  wy , wy  h
winz  0, 1
Fall 2009 revised
125
Reverse Transform: gluUnproject
(screen coords) (object coords)
glGetIntegerv (GL_VIEWPORT, viewport);
glGetDoublev (GL_MODELVIEW_MATRIX, mvmatrix);
glGetDoublev (GL_PROJECTION_MATRIX, projmatrix);
BACK
Fall 2009 revised
126
Debug “Blankscreen” Syndrome
Your program compiled
OK, but nothing on
screen?!
?
Check your graphics
pipeline

Unless OpenGL error
occurs, there is nothing
in the viewing frustum
 Probably the camera is
looking at somewhere
else
#define CHECK_OPENGL_ERROR(cmd) \
{ cmd; \
{ GLenum error; \
while ( (error = glGetError()) != GL_NO_ERROR) { \
printf( "[%s:%d] '%s' failed with error %s\n", \
__FILE__, __LINE__, #cmd, gluErrorString(error) ); }\
}}
Fall 2009 revised
BACK
127
Ambient Reflection
Local illumination models account for light
scattered from the light source only
Light may be scattered from all surfaces in
the scene. We are missing a lot of light,
typically over 50%
Ambient term = a coarse approximation to
this missing flux
This is a constant everywhere in the scene
BACK
Fall 2009 revised
128
Diffuse Reflection
Johann Heinrich Lambert
(1728 – 1777) was a Swiss
mathematician, physicist and
astronomer.
Lambertian scatters (wikipedia): the
irradiance landing on the area element
is proportional to the cosine of the
angle between the illuminating surface
and the normal.
When a Lambertian surface is viewed
from any angle, it has the same
radiance.
BACK
Fall 2009 revised
129
Specular Reflection
a
Effect of Shininess Coefficient a.
v
Fall 2009 revised
130
Blinn-Phong Model
I s  ks Ls r  v
a
n
r
l
n  l n
An alternate formulation
employs the half vector H
vl ˆ h
h
,h 
2
h
I s  k s Ls n  h 
a
l  n  l n
r  n  l n  l  n  l n
 2n  l n  l
Time-Consuming!
Fall 2009 revised
BACK
131
Plane after Transformation …
Given the transform:
Q (the plane P after transformation H):
Proof:
We require:
The first three components of p
(=0) correspond to some normal
vector. Hence, the normal after
transformation is
R t 
T

n  R n, H  

0
1


Fall 2009 revised
132
Example
Transformation:
Rot(y,-90)+(1,0,0)
y
(0,1,0)
(1,1,0)
Transformation matrix:
(0,0,1)
y+z-1=0
0
0
H 
1

0
x
z
 R t   RT
 0 1 

 0
 RT t 
 I 0
I 

0
1
1 


0
0
H 1  
 1

0
Fall 2009 revised
0 1
1 0
0 0
0 0
0
1
0
0
1
0
0
0
1
0
0

1
0
0
1

1
133
Example (cont)
0
0
H 1  
 1

0
y
(1,1,0)
(1,1,1)
(0,0,0)
z
x
0
1
0
0
1
0
0
0
0
0
1

1
0
0
q  pH 1  0 1 1  1
 1

0
  1 1 0 0
-x+y=0
Fall 2009 revised
0
1
0
0
1
0
0
0
BACK
134
0
0
1

1
s -f
gluLookAt (eye, center, up)
s
s
s
Change of Basis
LT
 world x   s[0] u[0]  f [0] eyex 
 world    s[1] u[1]  f [1]  eye 
y


 y 
 world z   s[2] u[2]  f [2] eyez 
xworld  Lxeye
xeye  L1 xworld  LT xworld
Equivalent to:
BACK
Fall 2009 revised
135
Idea of Lee and Koh (1995)
This rotation can be noted by Rx’(45) Rz(30)
second
first
Consider Rx’(45) as
Rz(30)Rx(45)Rz(-30)
Rx’(45)Rz(30)
=Rz(30)Rx(45)Rz(-30) Rz(30)
=Rz(30) Rx(45)
Fall 2009 revised
136
Animation (ref)
BACK
Fall 2009 revised
137
GL Version Query
#include <gl/glew.h>
#include <gl/glut.h>
#include <iostream>
using namespace std;
int main (int argc, char** argv)
{
glutInit (&argc,argv);
glewInit();
glutCreateWindow ("t");
//
}
cout
cout
cout
cout
cout
<<
<<
<<
<<
<<
"GL vendor: " << glGetString (GL_VENDOR) << endl;
"GL renderer: " << glGetString (GL_RENDERER) << endl;
"GL version: " << glGetString (GL_VERSION) << endl;
"GLSL version: " << glGetString (GL_SHADING_LANGUAGE_VERSION) << endl;
"GL extension: " << glGetString (GL_EXTENSIONS) << endl;
BACK
Fall 2009 revised
138
Download