Title: Graficacion
1Graficacion
- Curso de Ingenieria en Computacion
- Clave 115124
- Profesor Dr. Gueorgi Khatchatourov
2GENERAL INDEX
- Tema 1.- Aspectos generales de programación de
realidad virtual en OpenGL - Tema 2.- Lógica de transformaciones matriciales
en OpenGL -
- Tema 3.- Viewing
- Tema 4.- Transformations
- Tema 5.- Projection transformations
- Tema 6.- Viewport
- Tema 7.- Selection
- Tema 8.- Bitmaps
- Tema 9.- Texture Mapping
- Tema 10.- Blending
3Tema 1.- Aspectos generales de programación de
realidad virtual en OpenGL
- 1.1 Hardware structures for pixels on the
screen - 1.2 Aspects of Graphics Programming
- 1.3 Final part of the rendering process
- 1.4 Real-time Graphics as events-based
programming - 1.5.1 Call time control uso de
glutIdleFunc (1) - 1.5.2 Call time control uso de
glutIdleFunc (2) - 1.6.1 Other animation control uso de
glutIdleFunc - 1.6.2 Other animation control uso de
glutIdleFunc program single_double.c (1) - 1.6.3 Call time control uso de
glutIdleFunc program single_double.c
(2) - 1.7 Main loop control
- 1.8 Main loop control for drawing
- 1.9 OpenGL Primitives
- 1.10 OpenGL State Machine (II), (III),
(IV) - 1.11 Adaptation of OpenGL Examples to
VisualStudio
to return to general index
4Tema 2.- Lógica de transformaciones matriciales
en OpenGL
- 2.1 Let us analyze an example
- 2.2 continue the example
- 2.3 Geometric Transformations The
Pipeline - 2.4 Relation between the program and
matrix notation
to return to general index
5Tema 3.- Viewing
- 3.1 Viewing transformation (I de II)
- 3.2 Viewing transformation (II de II)
to return to general index
6Tema 4.- Transformaciones del modelo
- 4.1 Transformaciones del modelo I
- 4.2 Transformaciones básicas I
- 4.3 Transformaciones básicas II
- 4.5 Shadow matrix
- (1),(2),(3),(4),(5),(6),(7),(8),(
9) - 4.6 Shadow matrix (10)Tarea 1
- 4.7 Shadow matrix (11)Tarea 2
- 4.8 Reflexiones y transparencias I
- 4.9 Reflexiones y transparencias II
to return to general index
7Tema 5.- Projection transformations
- 5.1, Que significa "transformación de
proyección" - 5. 2,Opciones para transformación de proyección
- 5.3 Funciones de OpenGl para
- 5.4 glFrustum()
- 5. 5 gluPerspective()
- 5. 6 glOrtho()
to return to general index
8 Tema 6.- Viewport 6.1 Mapping
Drawing Coordinates to Window
Coordinates 6.2 Mapping Drawing
Coordinates to Window
Coordinates (2), (3), (4)
to return to general index
9Tema 7.- Selection
- 7.1 Lógica general
- 7.2 The Name Stack I y II
- 7.3 hits and selection buffer
- 7.4 Introducing the Name Stack
- 7.5 functions to manipulate the Name
Stack - 7.6 ejemplo de manipulación con el
Name Stack - 7.7 Name Stack ejemplo del
contenido de hit records - registrado en el selection
buffer - 7.8. Ilustración a lógica de Selection Bufer
to return to general index
10Tema 8.- Bitmaps
- void glBitmap.....................................
.......................(II), - Example 8-1 Drawing a Bitmapped Character
drawf.c...........................................
...........................(III), - F as a bitmap and itscorresponding bitmap
data......................................(IV), - Choosing a Color for the Bitmap...................
........(V)
to return to general index
11Tema 9.- Texture Mapping
- Contenido
- Organigrama de uso de texturas .
(I) - Steps in Texture Mapping .. (II),
- Naming a texture object, glGenTexture()...
(III), - Create a texture object and specify a
texture for it, glBindTexture()..................
.....................................(IV), - Modos de almacenamiento y las operaciones de
transferencia.. (V), - Specificar textura , glTexImage2D(). (V
I), - Substutute a part of texture with a sub
texture, glTexSubImage2D
..(VII) - Ejemplo de Aplicación de Texturas .....
(VIII)
to return to general index
12Tema 10.- Blending
- 10.1 Blending II official terminology
- 10.2. glBlendFunc()
- 10.1 Tabla de valores de argumentos de
glBlendFunc()
to return to general index
13Tema 12.-Light and Color
- 12.1 glEnable(GL_LIGHTi or
GL_LIGHTING) - 12.2 glEnable(GL_LIGHTING)
- 12.3
- 12.4
-
to return to general index
14 Tema 12.-Light and Color lógica está
subordinada al modelo de Phong
El modelo de Phong (en la fórmula arriba) es una
simulación computacional de leyes naturales de
generación de colores de iluminación en cada
pixel de la imagen. Modelo de iluminación en
OpenGl adapta el modelo de Phong. Y por lo tanto
la lógica de uso de iluminación en OpenGl
? la configuración de parámetros de
modelo de Phong mediante las rutinas de OpenGl
to return to general index
15 Tema 12.-Light and Color sentido de los
párametros del modelo de Phong
En el modelo de Phong (en la fórmula arriba
copiada de Wikipedia) la reflexión de una
superficie se divide en tres sub-componentes
ambiental, difusa, y speculiar (sub-indices
a, d , y s , respectivamente). Para el
cálculo de los componentes de luz difusa, y luz
speculiar, es necesario tomar en cuenta
siguientes vectores L de luz a la superficie,
N normal a la superficie, V de superficie al
mirador, R vector de reflexión del L de la
superficie. Los componentes se calculan por
separado para cada fuente de luz y luego se
suman. Letras k y i en la fórmula
corresponden a vectores que determinen las
propiedades de material de la superficie y de la
luz.
to return to general index
16 Tema 12.-Light and Color fragmento de la
máquina de OpenGl responsible de luz
to return to general index
17Tema 12.-Light and Color specificación de
glLightModel() de OpenGl glLightModel() de OpenGl
(I)
- NAME
- glLightModelf, glLightModeli, glLightModelfv,
glLightModeliv - set the lighting model
parameters - C SPECIFICATION
- void glLightModelf( GLenum pname, GLfloat param )
- void glLightModeli( GLenum pname, GLint param )
- PARAMETERS
- pname Specifies a single-valued lighting model
parameter. GL_LIGHT_MODEL_LOCAL_VIEWER and
GL_LIGHT_MODEL_TWO_SIDE are accepted. - param Specifies the value that param will be set
to. - C SPECIFICATION
- void glLightModelfv( GLenum pname, const GLfloat
params ) - void glLightModeliv( GLenum pname, const GLint
params ) - PARAMETERS
- pname Specifies a lighting model parameter.
GL_LIGHT_MODEL_AMBIENT, GL_LIGHT_MODEL_LOCAL_VIEWE
R, and GL_LIGHT_MODEL_TWO_SIDE are accepted. - params Specifies a pointer to the value or values
that params will be set to.
- DESCRIPTION
- glLightModel sets the lighting model parameter.
pname names a parameter and params gives the new
value. There are three lighting model parameters
- GL_LIGHT_MODEL_AMBIENT params contains four
integer or floating-point values that specify the
ambient RGBA intensity of the entire scene.
Integer values are mapped linearly such that the
most positive representable value maps to 1.0,
and the most negative representable value maps to
-1.0. Floating-point values are mapped directly.
Neither integer nor floating-point values are
clamped. The initial ambient scene intensity is
(0.2, 0.2, 0.2, 1.0). GL_LIGHT_MODEL_LOCAL_VIEWER
params is a single integer or floating-point
value that specifies how specular reflection
angles are computed. If params is 0 (or 0.0),
specular reflection angles take the view
direction to be parallel to and in the direction
of the -z axis, regardless of the location of the
vertex in eye coordinates. Otherwise, specular
reflections are computed from the origin of the
eye coordinate system. The initial value is 0.
GL_LIGHT_MODEL_TWO_SIDE params is a single
integer or floating-point value that specifies
whether one- or two-sided lighting calculations
are done for polygons. It has no effect on the
lighting calculations for points, lines, or
bitmaps. If params is 0 (or 0.0), one- sided
lighting is specified, and only the front
material parameters are used in the lighting
equation. Otherwise, two-sided lighting is
specified. In this case, vertices of back-facing
polygons are lighted using the back material
parameters, and have their normals reversed
before the lighting equation is evaluated.
Vertices of front-facing polygons are always
lighted using the front material parameters, with
no change to their normals. The initial value is
0.
18Tema 12.-Light and Color specificación de
glLightModel() de OpenGl (II)
- In RGBA mode, the lighted color of a vertex is
the sum of the material emission intensity, the
product of the material ambient reflectance and
the lighting model full-scene ambient intensity,
and the contribution of each enabled light
source. Each light source contributes the sum of
three terms ambient, diffuse, and specular. The
ambient light source contribution is the product
of the material ambient reflectance and the
light's ambient intensity. The diffuse light
source contribution is the product of the
material diffuse reflectance, the light's diffuse
intensity, and the dot product of the vertex's
normal with the normalized vector from the vertex
to the light source. The specular light source
contribution is the product of the material
specular reflectance, the light's specular
intensity, and the dot product of the normalized
vertex-to- eye and vertex-to-light vectors,
raised to the power of the shininess of the
material. All three light source contributions
are attenuated equally based on the distance from
the vertex to the light source and on light
source direction, spread exponent, and spread
cutoff angle. All dot products are replaced with
0 if they evaluate to a negative value. The alpha
component of the resulting lighted color is set
to the alpha value of the material diffuse
reflectance. - ERRORS
- GL_INVALID_ENUM is generated if pname is not an
accepted value. - GL_INVALID_OPERATION is generated if glLightModel
is executed between the execution of glBegin and
the corresponding execution of glEnd. - ASSOCIATED GETS
- glGet with argument GL_LIGHT_MODEL_AMBIENT
- glGet with argument GL_LIGHT_MODEL_LOCAL_VIEWER
- glGet with argument GL_LIGHT_MODEL_TWO_SIDE
- glIsEnabled with argument GL_LIGHTING
- SEE ALSO
- glLight, glMaterial
19 Tema 12.-Light and Color glEnable(GL_LIGHTi
or GL_LIGHTING)
glEnable(GL_LIGHTi) / incluir la luz i en la
ecuaciòn de alumbramiento ver glLightModel y
glLight/ glEnable(GL_LIGHTING) / usar los
parametros vigentes de alumbramiento para càlculo
del color de vertice o indice Si no està
habilitado GL_LIGHTING , entonces, el color o
indice corriente se asocìa con cada vèrtice /
to return to general index
20 Tema 11.- Stencil
to return to general index
21Tema 1.- Aspectos generales de programación de
realidad virtual en OpenGL
to return to index
22Aspectos generales Hardware structures for
pixels on the screen
- Framebuffermemory formed by a set of bitplanes
- Bitplane a set of bits that has one-to-one
correspondence to the set of the screen pixels
to return to index
23Aspectos generales Aspects of Graphics
Programming
- Rendering model-based image generation
- Rendering mode
- Retained mode
- Immediate mode
- Model
- Model primitives
- Spacing Projection, light, texture, fog
- Real-time Graphics as events-based programming
to return to index
24Aspectos generales Final part of the rendering
process
framebuffer
control
Interpretation
glFlush(void) glutSwapBuffers()
Image on the screen
to return to index
25Aspectos generales Real-time Graphics as
events-based programming
- Main loop
- Registering a callback function
- The user-initiated events for calling back
- reshaping,
- keyboard,
- and changing mouse state
to return to index
26Aspectos generales Call time control uso de
glutTimerFunc (1)
- This function, glutTimerFunc, takes the name of a
function to call and the amount of time to wait
before calling the function - void glutTimerFunc(unsigned int msecs, void
(func)(int value), int value) - This code sets up GLUT to wait msecs
milliseconds before calling func. Pass a
user-defined value in the value parameter. The
function called by the timer has the following
prototype - void TimerFunction(int value)
- Unlike the Windows timer, this function is
fired only once. To effect a continuous
animation, reset the timer again in the timer
function.
to return to index
27Aspectos generales Call time control uso de
glutTimerFunc (2)
- void TimerFunction(int value)
- ......
- glutPostRedisplay()
- glutTimerFunc(33,TimerFunction, 1)
-
- void SetupRC(void) // Setup the rendering state
- // Set clear color to blue
- glClearColor(0.0f, 0.0f, 1.0f, 1.0f)
-
- int _tmain(int argc, _TCHAR argv)
- glutInit(argc, (char )argv)
- glutInitDisplayMode(GLUT_DOUBLE GLUT_RGB)
- glutCreateWindow ((char )argv0)
- glutDisplayFunc(RenderScene)
- glutReshapeFunc(ChangeSize)
- glutTimerFunc(33, TimerFunction, 1)
to return to index
28Aspectos generales Main loop control
- I TimerFunction
- II SetupRC(void)
- III glutInitDisplayMode(GLUT_DOUBLE
GLUT_RGB) - IV glutCreateWindow ((char )argv0)
- V RenderScene
- VI ChangeSize
Configure rendering before starting the main
loop IIIII IV
Main loop
I, V
I, (V), (VI)
I, (V), (VI)
Interaction with Main loop control
I recursive request to be called at each cycle
V single request to be called at the 1st cycle
and then when needed
VI single request to be called when needed
to return to index
29Aspectos generales Main loop control for drawing
- void glutDisplayFunc(void (func)(void))
Specifies the function that's called whenever the
contents of the window need to be redrawn. The
contents of the window may need to be redrawn - the window is initially opened,
- the window is popped and window damage is
exposed, - glutPostRedisplay() is explicitly called.
glutPostRedisplay() causes Main Loop control to
call display callback function for re-rendering
after other events have been processed.
void glutReshapeFunc(void (func)(int width, int
height)) Specifies the function that's called
whenever the window is resized or moved. The
argument func is a pointer to a function that
expects two arguments, the new width and height
of the window. Typically, func calls glViewport,
so that the display is clipped to the new size,
and it redefines the projection matrix so that
the aspect ratio of the projected image matches
the viewport, avoiding aspect ratio distortion.
If glutReshapeFunc isn't called or is
deregistered by passing NULL, a default reshape
function is called, which calls glViewport(0, 0,
width, height).
to return to index
30Aspectos generales Other animation control uso
de glutIdleFunc()
- glutIdleFunc sets the global idle callback.
- Usage
- void glutIdleFunc(void (func)(void))
- func The new idle callback function.
- Description
- glutIdleFunc sets the global idle callback to be
func so a GLUT program can perform background
processing tasks or continuous animation when
window system events are not being received. If
enabled, the idle callback is continuously called
when events are not being received. The callback
routine has no parameters. - The current window and current menu will not be
changed before the idle callback. Programs with
multiple windows and/or menus should explicitly
set the current window and/or current menu and
not rely on its current setting. - The amount of computation and rendering done in
an idle callback should be minimized to avoid
affecting the programs interactive response. In
general, not more than a single frame of
rendering should be done in an idle callback. - Passing NULL to glutIdleFunc disables the
generation of the idle callback.
to return to index
31Aspectos generales Other animation control uso
de glutIdleFunc() program single_double.c de
Ed.Angel book
- static GLfloat spin 0.0
- int singleb, doubleb
- void displayd(void)
- glClear (GL_COLOR_BUFFER_BIT)
- glRectf (-25.0, -25.0, 25.0, 25.0)
- glutSwapBuffers ()
-
- void displays(void)
- glClear (GL_COLOR_BUFFER_BIT)
- glRectf (-25.0, -25.0, 25.0, 25.0)
- glFlush()
-
- void spinDisplay (void)
- spin spin 2.0
- if (spin gt 360.0)
- spin spin - 360.0
- glutSetWindow(singleb)
- glLoadIdentity()
- glRotatef (spin, 0.0, 0.0, 1.0)
- glutPostRedisplay()
- glutSetWindow(doubleb)
- glLoadIdentity()
- glRotatef (spin, 0.0, 0.0, 1.0)
- glutPostRedisplay()
-
- void myinit (void)
- glClearColor (0.0, 0.0, 0.0, 1.0)
- glColor3f (1.0, 1.0, 1.0)
- glShadeModel (GL_FLAT)
-
- ? continua en la siguiente lamina
to return to index
32Aspectos generales Other animation control uso
de glutIdleFunc()
- ?continuación
- void mouse(int btn, int state, int x, int y)
- if(btnGLUT_LEFT_BUTTON stateGLUT_DOWN)
glutIdleFunc(spinDisplay) - if(btnGLUT_MIDDLE_BUTTON stateGLUT_DOWN)
glutIdleFunc(NULL) -
- void myReshape(int w, int h)
- glViewport(0, 0, w, h)
- glMatrixMode(GL_PROJECTION)
- glLoadIdentity()
- if (w lt h) glOrtho (-50.0, 50.0,
-50.0(GLfloat)h/(GLfloat)w, - 50.0(GLfloat)h/(GLfloat)w, -1.0, 1.0)
- else glOrtho (-50.0(GLfloat)w/(GLfloat)h,
- 50.0(GLfloat)w/(GLfloat)h, -50.0, 50.0,
-1.0, 1.0) - glMatrixMode(GL_MODELVIEW)
- glLoadIdentity ()
- / Main Loop Open window with initial window
size, title bar, RGBA display mode, and handle
input events. / - int main(int argc, char argv)
- glutInit(argc,argv)
- glutInitDisplayMode (GLUT_SINGLE GLUT_RGB)
- singlebglutCreateWindow("single buffered")
- myinit ()
- glutDisplayFunc(displays)
- glutReshapeFunc (myReshape)
- glutIdleFunc (spinDisplay)
- glutMouseFunc (mouse)
- glutInitDisplayMode (GLUT_DOUBLE GLUT_RGB)
- doublebglutCreateWindow("double buffered")
- myinit ()
- glutDisplayFunc(displayd)
- glutReshapeFunc (myReshape)
- glutIdleFunc (spinDisplay)
- glutMouseFunc (mouse)
- glutMainLoop()
to return to index
33Aspectos generales OpenGL Primitives
back
The VertexA Position in Space A vertex a
coordinate in 2D or 3D space. The geometric
definition of a vertex is not just a point in
space, but rather the point at which an
intersection of two lines or curves occurs. This
is the essence of primitives. In both 2D and
3D, when you draw an object, you actually compose
it with several smaller shapes called primitives.
A primitive is simply the interpretation of a
set or list of vertices into some shape drawn on
the screen. There are 10 primitives in OpenGL,
from a simple point drawn in space to a closed
polygon of any number of sides. Primitives are
one- or two-dimensional entities or surfaces such
as points, lines, and polygons (a flat,
multisided shape) that are assembled in 3D space
to create 3D objects. For example, a
three-dimensional cube consists of six
two-dimensional squares, each placed on a
separate face. Each corner of the square (or of
any primitive) is represented by a vertex.
to return to index
34Aspectos generales OpenGL State Machine
back
Drawing 3D graphics is a complicated affair. For
a given piece of geometry, many things can affect
how it is drawn. Is a light shining on it? What
are the properties of the light? What are the
properties of the material? Which, if any,
texture should be applied? The list could go on
and on. We call this collection of variables the
state of the pipeline. A state machine is an
abstract model of a collection of state
variables, all of which can have various values,
be turned on or off, and so on. When a state
value is set, it remains set until some other
function changes it. Many states are simply on
or off. Lighting, for example, is either turned
on or off. Geometry drawn without lighting is
drawn without any lighting calculations being
applied to the colors set for the geometry. Any
geometry drawn after lighting is turned back on
is then drawn with the lighting calculations
applied.
to return to index
35Aspectos generales OpenGL State Machine (II)
back
To turn these types of state variables on and
off, you use void glEnable(GLenum capability)
You turn the variable back off with the
corresponding function void glDisable(GLenum
capability) For the case of lighting, for
instance, you can turn it on by using the
following glEnable(GL_LIGHTING) And you turn
it back off with this functionglDisable(GL_LIGHT
ING) To test a state variable to see whether
it is enabled, use Glboolean glIsEnabled(GLenum
capability)
to return to index
36Aspectos generales OpenGL State Machine (III)
back
Not all state variables, however, are simply on
or off. Many of the OpenGL functions set up
values that "stick" until changed. You can query
what these values are at any time. These four
query functions are prototyped thus void
glGetBooleanv(GLenum pname, GLboolean params)
void glGetDoublev(GLenum pname, GLdouble
params) void glGetFloatv(GLenum pname, GLfloat
params) void glGetIntegerv(GLenum pname, GLint
params) Each function returns a single value
or a whole array of values, storing the results
at the address you supply.
to return to index
37Aspectos generales OpenGL State Machine
(IV)Saving and Restoring States
back
OpenGL also has a convenient mechanism for saving
a whole range of state values and restoring them
later. A single OpenGL state value or a whole
range of related state values can be pushed on
the attribute stack with the following
command void glPushAttrib(GLbitfield mask)
Values are correspondingly retrieved with this
command void glPopAttrib(GLbitfield mask)
The argument to these functions is a bitfield.
This means that you use a bitwise mask, which
allows you to perform a bitwise OR (in C using
the operator) of multiple state values with a
single function call. For example, you could save
the lighting and texturing state with a single
call like this glPushAttrib(GL_TEXTURE_BIT
GL_LIGHTING_BIT)
to return to index
38Aspectos generales Adaptation of OpenGL Examples
to VisualStudio back
- What to do
- Put headers into a proper directory
- Put libraries into a proper directory
- Choose "consol application" as configuration for
VisualStudio project - Correct the source code of an example
to return to index
39Tema 2 Lógica de transformaciones matriciales en
OpenGL back
to return to index
40Logics of the matrix transformation (I de
IV)Let us analyze an example back
Only the model of an object is transformed below
the view and projection stay out of the scope of
the program void display(void) glClear(GL_COLOR
_BUFFER_BIT) // save current matrix in the
stack and duplicate it at once glPushMatrix()
//multiply current matrix with matrix of rotation
around Z-axis glRotatef(spin, 0.0, 0.0,
1.0) // apply the obtained current matrix to a
fixed white rectangle glColor3f(1.0, 1.0,
1.0) glRectf(-25.0, -25.0, 25.0,
25.0) //restore current matrix
glPopMatrix() //swap framebuffers and display
scene glutSwapBuffers()
to return to index
41Logics of the matrix transformation (II de IV)
continue the example back
void reshape(int w, int h) //modify
viewport glViewport (0, 0, (GLsizei) w,
(GLsizei) h) //apply subsequent matrix
operation to the projection matrix
stack glMatrixMode(GL_PROJECTION) glLoadIdentity(
) // transform the current matrix by setting
// (explicitly) a volume for orthographic
projection and // (implicitly) the matrix of the
default viewpoint glOrtho(-50.0, 50.0, -50.0,
50.0, -1.0, 1.0) // apply subsequent matrix
operation to the modelview matrix
stack glMatrixMode(GL_MODELVIEW) glLoadIdentity()
to return to index
42Logics of the matrix transformation (III de IV)
back
Geometric Transformations The Pipeline
Organizing the transformations as pipeline means
that projection and modelview matrices co-exist
in parallel mode. Changing matrixmode from
modelview to projection and vice versa in your
program does not erase actual modelview or
projection matrix. OpenGL multiplies
automatically vectors represented in transformed
eye coordinates by the projection matrix.
to return to index
43Logics of the matrix transformation (IV de IV)
Relation between the program and matrix notation
back
Consider the following code sequence glMatrixMo
de(GL_MODELVIEW) glLoadIdentity() glMultMatrixf(
N) / apply transformation N / glMultMatrixf(M)
/ apply transformation M / glMultMatrixf(L)
/ apply transformation L / glBegin(GL_POINTS)
glVertex3f(v) / draw transformed vertex v
/ glEnd() The transformed vertex is NMLv
N(M(Lv))
to return to index
443.- Viewing
to return to index
back
45Viewing transformation (I de II)
- As a part of modelview transformation, the
viewing transformation is specified with
gluLookAt(). - If gluLookAt() was not called, the camera has a
default position and orientation. By default, the
camera is situated at the origin, points down the
negative z-axis, and has an up-vector of (0, 1,
0).
to return to index
back
46Viewing transformation (II de II)
- void gluLookAt(GLdouble eyex, GLdouble eyey,
GLdouble eyez, GLdouble centerx, GLdouble
centery, GLdouble centerz, GLdouble upx, GLdouble
upy, GLdouble upz) - Defines a viewing matrix and multiplies it to the
right of the current matrix. The desired
viewpoint is specified by eyex, eyey, and eyez.
The centerx, centery, and centerz arguments
specify any point along the desired line of
sight, but typically they're some point in the
center of the scene being looked at. The upx,
upy, and upz arguments indicate which direction
is up (that is, the direction from the bottom to
the top of the viewing volume). - In the default position (see previous slide), the
camera is at the origin, is looking down the
negative z-axis, and has the positive y-axis as
straight up. This is the same as calling - gluLookat (0.0, 0.0, 0.0, 0.0, 0.0, -100.0, 0.0,
1.0, 0.0)
to return to index
back
474.-Transformaciones del modelo
back
to return to index
48Transformaciones del modelo I
- Las transformaciones del modelo se pueden dividir
en las básicas y las derivadas - Las básicas incluyen
- Cualquier combinación de la Traslación, la
rotación y escalamiento, o multiplicación por una
dada matriz 4x4 - Las derivadas son aquellas que se usan para
efectos especiales tales como sombra, espejo,
selección,
back
to return to index
49Transformaciones básicas I
- Translate
- void glTranslatefd(TYPEx, TYPE y, TYPEz)
- Multiplies the current matrix by a matrix that
moves (translates) an object by the given x, y,
and z values (or moves the local coordinate
system by the same amounts). - Rotate
- void glRotatefd(TYPE angle, TYPE x, TYPE y,
TYPE z) - Multiplies the current matrix by a matrix that
rotates an object (or the local coordinate
system) in a counterclockwise direction about the
ray from the origin through the point (x, y, z).
The angle parameter specifies the angle of
rotation in degrees. - Scale
- void glScalefd(TYPEx, TYPE y, TYPEz)
- Multiplies the current matrix by a matrix that
stretches, shrinks, or reflects an object along
the axes. Each x, y, and z coordinate of every
point in the object is multiplied by the
corresponding argument x, y, or z. With the local
coordinate system approach, the local coordinate
axes are stretched, shrunk, or reflected by the
x, y, and z factors, and the associated object is
transformed with them.
back
to return to index
50Transformaciones básicas II
- void glLoadMatrixfd(const TYPE m) Sets the
sixteen values of the current matrix to those
specified by m. - void glMultMatrixfd(const TYPE m)
Multiplies the matrix specified by the sixteen
values pointed to by m by the current matrix and
stores the result as the current matrix. - The argument for both these commands is a vector
of sixteen values (m1, m2, ... , m16) that
specifies a matrix M as follows - Note All matrix multiplication with OpenGL
occurs as follows Suppose the current matrix is
C and the matrix specified with glMultMatrix()
or any of the transformation commands is M. After
multiplication, the final matrix is always CM. - Tarea leer "Advanced Matrix Manipulation ",
Chapter 4. Geometric Transformations The
Pipeline, OpenGL SuperBible
back
to return to index
51Shadow matrix (1)
- La matrix de sombra es una especie de la
transformation "modelview" - Dada L como vector de la posición de la
fuente de luz, un plano, y un punto s en espacio,
la sombra del punto al plano se representa como
sr(s-L) donde el parametro r se busca de la
condicion que sr(s-L) pertenece al plano en
cuestion. - Elijamos la representación del plano mediante
la cuádruple a, b, c, d, donde na, b, c es
un vector ortonormal al plano y d es el
desplazamiento del plano desde el origen del
sistema de coordenadas a lo largo del eje
generado por n). - Obviamente, el vector (x,y,z) pertenece al
plano si y solo si se cumple la ecuación - axbyczd0.
back
to return to index
52Shadow matrix (2)
- La ecuacion anterior implica
- a(sxr(sx- Lx))b(syr(sy- Ly))c(szr(sz-
Lz))d0 - De donde se tiene
-
-
()
back
to return to index
53Shadow matrix (3)
- En otras palabras, para cada s del espacio se ha
encontrado el mapeo -
() -
- donde r es el valor de () de la diapositiva
anterior.
back
to return to index
54Shadow matrix (4)
- La última parte de la búsqueda de la matriz de
sombra ("shadow matrix") usa las dependencias
mencionadas para encontrar los elementos de tal
matrix Msombra, que el mapeo del () se
representa como - ssombra Msombra s
back
to return to index
55Shadow matrix (5)
- Los elementos de la matriz de sombra tienen una
flexibilidad para la definicion de sus
coeficientes, basada en la equivalencia -
-
- Re-escribimos ()
-
()
back
to return to index
56Shadow matrix (6)
- Multiplicamos todos componentes del vector en
() por - (estamos usando la equivalencia antemencionada).
Se tiene - Desarrollando las últimas expresiones, se tiene
back
to return to index
57Shadow matrix (7)
back
to return to index
58Shadow matrix (8)
back
to return to index
59Shadow matrix (9)
- Finalmente, se tiene
- Tarea Comparen cada elemento de la M con los
elementos correspondientes del siguiente código
de la "Superbiblia"
back
to return to index
60Shadow matrix (10)(tarea)
- void gltMakeShadowMatrix(GLfloat
vPlaneEquation, GLfloat vLightPos, GLfloat
destMat) -
- GLfloat dot
- // Dot product of plane and light position
- dot vPlaneEquation0vLightPos0
vPlaneEquation1vLightPos1 - vPlaneEquation2vLightPos2
vPlaneEquation3vLightPos3 - // Now do the projection
- // First column
- destMat0 dot - vLightPos0
vPlaneEquation0 - destMat4 0.0f - vLightPos0
vPlaneEquation1 - destMat8 0.0f - vLightPos0
vPlaneEquation2 - destMat12 0.0f - vLightPos0
vPlaneEquation3 - // Second column
- destMat1 0.0f - vLightPos1
vPlaneEquation0 - destMat5 dot - vLightPos1
vPlaneEquation1 - destMat9 0.0f - vLightPos1
vPlaneEquation2
back
to return to index
61Shadow matrix (11). Tarea 2
- En que orden hay que construir los siguientes
componentes de la imagen? -
- Piso
- Objeto
- Sombra del objeto en el piso
back
to return to index
62Reflexiones y transparencias I
- Componentes del modelo son
- Piso
- Fuente de luz
- Objeto
- Los mecanismos involucrados
- Ecritura normal al framebuffer (borrando el
contenido anterior) - Escritura mediante blending (mezclando el nuevo
contenido con lo anterior) - Lógica de reflexión
- Reflejar mundo (luz y objeto) respecto el piso
- Dibujar el mundo reflejado
- Habilitar GL_ BLEND
- Dibujar el piso, mezclándolo (BLENDING) con el
contenido actual del framebuffer - Deshabilitar GL_ BLEND
- Restaurar el mundo
- Dibujar el mundo
back
to return to index
63Reflexiones y transparencias II
- glPushMatrix()
// recordar la matriz actual - PushLightStack() //
recordar la posicion de luz actual - fLightMirr()
// invertir posición de la fuente de luz respecto
el piso - glFrontFace(GL_CW) // cambiar
orientacion de poligonos para invertir los lados
delanteros y traseros - glPushMatrix() //
recordar la matriz actual - / dibujar mundo invertido /
- glScalef(1.0f, -1.0f, 1.0f)
- glTranslatef(0.0f, 2.0fyground, 0.0f)
- Draw_Objects_Color()
- / restaurar el mundo normal/
- glPopMatrix() //restaurar
matriz - glFrontFace(GL_CCW) //
restaurar orientación - PopLightStack()
//restaurar posición de luz - // Dibujar el piso transparente sobre el mundo
reflejado - glDisable(GL_LIGHTING)
-
glEnable(GL_BLEND) - glBlendFunc(GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA) - DrawGround()
- // desabilitar transparencia
back
to return to index
645.- Proj. Transf. I que significa
to return to index
back
65Projection Transformations II
- Hay dos opciones
- Proyección ortográfica
- Proyeccion de perspectiva
- Los parámetros para los programas de control de
la proyeccián se indican en los terminos de la
cámara.Es decir, - la 3a coordenada se dirige hacia la cámara
- La 2a hacia el vector de la proyeccián del vector
"up" (como aquél de gluLookAt()) por el plano
ortogonal al eje de la 3a coordenada - La 1a es orientada hacia el vector del producto
cruz de los vectores pertenecientes a los ejes de
la 2a y la 3a
back
to return to index
66Projection Transformations III
- glMatrixMode(GL_PROJECTION)
- glLoadIdentity()
- luego siguen opcionalmente
- glFrustum() //1a opción de la proyección
perspectiva - gluPerspective() //2a opción de la proyección
perspectiva - glOrtho() // proyección
ortográfica
back
to return to index
676.-Viewport
to return to index
back
68Viewports Mapping Drawing Coordinates to Window
Coordinates
back
to return to index
69Viewports Mapping Drawing Coordinates to Window
Coordinates (2)
The Viewport Transformation Together, the
projection transformation and the viewport
transformation determine how a scene gets mapped
onto the computer screen. The projection
transformation specifies the mechanics of how the
mapping should occur, and the viewport indicates
the shape of the available screen area into which
the scene is mapped. Since the viewport specifies
the region the image occupies on the computer
screen, you can think of the viewport
transformation as defining the size and location
of the final processed photograph - for example,
whether the photograph should be enlarged or
shrunk. The arguments to glViewport() describe
the origin of the available screen space within
the window - (0,0) in this example - and the
width and height of the available screen area,
all measured in pixels on the screen. This is why
this command needs to be called within reshape()
- if the window changes size, the viewport needs
to change accordingly. Note that the width and
height are specified using the actual width and
height of the window often, you want to specify
the viewport this way rather than giving an
absolute size.
back
to return to index
70Viewports Mapping Drawing Coordinates to Window
Coordinates (3)
void glViewport(GLint x, GLint y, GLsizei width,
GLsizei height) Defines a pixel rectangle in the
window into which the final image is mapped. The
(x, y) parameter specifies the lower-left corner
of the viewport, and width and height are the
size of the viewport rectangle. By default, the
initial viewport values are (0, 0, winWidth,
winHeight), where winWidth and winHeight are the
size of the window.
back
to return to index
71Viewports Mapping Drawing Coordinates(4)
Reshape Callback Function to draw into 2D system
To create a simple, basic two-dimensional
coordinate system into which you can draw a few
objects, call glutReshapeFunc(reshape), where
reshape() is the following function (Reshape
Callback Function) void reshape (int w, int
h) glViewport (0, 0, (GLsizei) w, (GLsizei)
h) glMatrixMode (GL_PROJECTION) glLoadIdentity
() gluOrtho2D (0.0, (GLdouble) w, 0.0,
(GLdouble) h) The internals of GLUT will pass
this function two arguments the width and
height, in pixels, of the new, moved, or resized
window. glViewport() adjusts the pixel rectangle
for drawing to be the entire new window. The next
three routines adjust the coordinate system for
drawing so that the lower-left corner is (0, 0),
and the upper-right corner is (w, h).
back
to return to index
727.- Selection Lógica general
- Re-dibujar virtualmente la imagen, asignando como
viewport una region pequena alrededor del cursor
Entrar al modo de seleccion (GL_SELECT)
Asignar una estructura para selection buffer (SB)
Mouse click
"Bautizar" unos primitivos y dibujarlos
virtualmente contando los "hits" y registrando
los resultados en un buffer temporal (BT)
Analizar e interpretar los registros de los
"hits" en SB
OpenGl escribir al SB la informacion del BT
sobre los "hits"
Regresar al modo normal (GL_RENDER)
to return to index
back
73Selection The Name Stack I
- The OpenGL API provides a mechanism for picking
objects in a 3D scene. It allows to detect which
objects are bellow the mouse or in a square
region of the OpenGL window. The steps involved
in detecting are - 1. Get the window coordinates of the mouse
- 2. Enter selection mode
- 3. Redefine the viewing volume so that only a
small area of the window around the cursor is
rendered - 4. Render the scene, either using all primitives
or only those relevant to the picking operation - 5. Exit selection mode and identify the objects
which were rendered on that small part of the
screen.
back
to return to index
74Selection The Name Stack II
- In order to identify the rendered objects using
the OpenGL API you must name all relevant objects
in your scene. The OpenGL API allows you to give
names to primitives, or sets of primitives
(objects). When in selection mode, a special
rendering mode provided by the OpenGL API, no
objects are actually rendered in the framebuffer.
Instead the names of the objects (plus depth
information) are collected in an array. For
unnamed objects, only depth information is
collected.
back
to return to index
75Selection hits and selection buffer
- Terminology
- a hit occurs whenever a primitive is rendered
in selection mode. REGRESAR a "logica de
Selection" - Hit records are stored in the selection buffer.
- Functionality
- Upon exiting the selection mode OpenGL returns
the selection buffer with the set of hit records.
- Since OpenGL provides depth information for
each hit the application can then easily detect
which object is closer to the user.
back
to return to index
767.8. Ilustración a lógica de construcción de
Selection Bufer
Hay nombre(s) en name stack?
Si un primitivo se dibuja anónimo, busque z-min
y z-max de todos sus vertices para escribirlos en
hit record anónimo
GL_SELECT
Dibujando un primitivo
Cuantos son?
El primitivo cruza el volumen de vista?
Si un primitivo se dibuja cuando hay uno o mas
nombres en name stack, incierta al registro el
número total de los nombres luego cada de los
nombres del hit y, finalmente, z-min y z-max de
todos los vértices relacionados a los primitivos
de "hits"
min max min
max
back
to return to index
77Selection Introducing the Name Stack
- As the title suggests, the names you assign to
objects are stored in a stack. Actually you don't
give names to objects, as in a text string.
Instead you number objects. Nevertheless, the
term name is used in OpenGL instead of number. - When an object is rendered, if it intersects the
new viewing volume, a hit record is created. The
hit record contains the names currently on the
name stack plus the minimum and maximum depth for
the object. - Note A hit record is created even if the name
stack is empty, in which case it only contains
depth information. If more objects are rendered
before the name stack is altered or the
application leaves the selection mode, then the
depth values stored on the hit record are altered
accordingly. -
- A hit record is stored on the selection buffer
only when - the current contents of the name stack are
altered - or when the application leaves the selection
mode. - The rendering function for the selection mode
therefore is responsible for the contents of the
name stack as well as the rendering of
primitives.
back
to return to index
78Selection functions to manipulate the Name Stack
- void glInitNames(void) This function
creates an empty name stack. You are required to
call this function to initialize the stack prior
to pushing names. void glPushName(GLuint name)
Adds name to the top of the stack. The stacks
maximum dimension is implementation dependent,
however according to the specs it must contain at
least 64 names which should prove to be more than
enough for the vast majority of applications.
Nevertheless if you want to be sure you may query
the state variable GL_NAME_STACK_DEPTH (use
glGetIntegerv (GL_NAME_STACK_DEPTH)). Pushing
values onto the stack beyond its capacity causes
an overflow error GL_STACK_OVERFLOW. void
glPopName() Removes the name from top of the
stack. Popping a value from an empty stack causes
an underflow, error GL_STACK_UNDERFLOW. void
glLoadName(GLunit name) This function replaces
the top of the stack with name. It is the same as
calling glPopName() - glPushName(name)
- Note Calls to the above functions are ignored
when not in selection mode. This means that you
may have a single rendering function with all the
name stack functions inside it. When in the
normal rendering mode the functions are ignored
and when in selection mode the hit records will
be collected. - Note You can't place these functions inside a
glBegin glEnd construction, which is kind of
annoying since that will require a new rendering
function for the selection mode in some cases.
back
to return to index
79Selection un ejemplo de manipulación con el
Name Stack
- define BODY 1
- define HEAD 2
- ...
- void renderInSelectionMode()
- glInitNames() / create an empty stack. This
is required before any - other operation on the stack
such as Load, Push or Pop. / - glPushName(BODY) /A name is pushed onto the
stack. The stack -
now contains a single name. / - drawBody() / draw something. If any of the
primitives called in here intersects the viewing
volume a hit record is created. The contents of
the hit record will be the name currently on the
name stack, BODY, plus the minimum and maximum
depth values for those primitives that intersect
the viewing volume / - glPopName() /Removes the name of the top of
the stack. Since the stack had a single item, it
will now be empty. The name stack has been
altered so if a hit record was created in 2 it
will be saved in the selection buffer / - glPushName(HEAD) /A name is pushed onto the
stack. The stack now contains a single name
again. The stack has been altered, but there is
no hit record so nothing goes into the selection
buffer / - drawHead() /Another function that renders
OpenGL primitives. Again if any of the primitives
intersects the viewing volume a hit record is
created / - drawEyes() /Yet another function which
renders OpenGL primitives. If any of the
primitives in here intersects the viewing volume
and a hit record already exists from 6, the hit
record is updated accordingly. The names
currently in the hit record are kept, but if any
of the primitives in drawEyes() has a smaller
minimum, or a larger maximum depth, then these
new values are stored in the hit record. If the
primitives in drawEyes() do intersect the viewing
volume but there was no hit record from drawHead
then a new one is created. / - glPopName() /The name on the top of the
stack is removed. Since the stack had a single
name the stack is now empty. Again the stack has
been altered so if a hit record was created it
will be stored in the selection buffer / - drawGround() /If any if the primitives
called in here intersects the viewing volume a
hit record is created. The stack is empty, so no
names will be stored in the hit record, only
depth information. If no alteration to the name
stack occurs after this point, then the hit
record created will only be stored in the
selection buffer when the application leaves the
selection mode. This will be covered later on the
tutorial. / -
back
to return to index
80Selection Name Stack ejemplo del contenido de
hit records registrado en el selection buffer
back
to return to index
818.- Bitmaps back
A bitmap is a rectangular array of 0s and 1s
that serves as a drawing mask for a corresponding
rectangular portion of the window. Suppose
you're drawing a bitmap and that the current
raster color is red -- Wherever there's a 1 in
the bitmap, the corresponding pixel is replaced
by a red pixel (or combined with a red pixel,
depending on which per-fragment operations are in
effect. -- If there's a 0 in the bitmap, the
contents of the pixel are unaffected. The most
common use of bitmaps is for drawing characters
on the screen.
to return to index
back
82Bitmaps(II) void glBitmap()
- Once you've set the desired raster position, you
can use the glBitmap() command to draw the data. - void glBitmap(GLsizei width, GLsizei height,
GLfloat xbo, GLfloat ybo, GLfloat xbi, GLfloat
ybi, const GLubyte bitmap) - Draws the bitmap specified by bitmap, which is a
pointer to the bitmap image. The origin of the
bitmap is placed at the current raster position.
If the current raster position is invalid,
nothing is drawn, and the raster position remains
invalid. The width and height arguments indicate
the width and height, in pixels, of the bitmap.
The width need not be a multiple of 8, although
the data is stored in unsigned characters of 8
bits each. (In the F example, it wouldn't matter
if there were garbage bits in the data beyond the
tenth bit since glBitmap() was called with a
width of 10, only 10 bits of the row are
rendered.) Use xbo and ybo to define the origin
of the bitmap (positive values move the origin up
and to the right of the raster position negative
values move it down and to the left) xbi and ybi
indicate the x and y increments that are added to
the raster position after the bitmap is
rasterized (see Figure 8-2). - Figure 8-2 Bitmap and Its Associated Parameters
back
to return to index
83Bitmaps(III) Example 8-1 Drawing a Bitmapped
Character drawf.c back
include GLubyte rasters24 0xc0, 0x00,
0xc0, 0x00, 0xc0, 0x00, 0xc0, 0x00, 0xc0,
0x00, 0xff, 0x00, 0xff, 0x00, 0xc0, 0x00, 0xc0,
0x00, 0xc0, 0x00, 0xff, 0xc0, 0xff, 0xc0 void
init(void) glPixelStorei (GL_UNPACK_ALIGNMENT,
1) / Sets the
pixel-storage mode,
GL_UNPACK_ALIGNMENT Specifies the alignment
requirements for the start of each pixel row in
memory. The
allowable values are 1 (byte-alignment), 2 (rows
aligned to even-numbered bytes), 4 (word
alignment), and 8 (rows
start on double-word boundaries). Es decir, si,
p.e., el ancho de la fila es 10, y por lo tanto,
el 2o byte es incompleto,
para evitar cualquier duda, asignamos "
GL_UNPACK_ALIGNMENT 1" para
decir al OpenGl que la siguiente fila
inicia desde el proximo byte inmediato despues
del byte incompleto, see more
details in Discusion_sobre_alignment.doc
/ glClearColor (0.0, 0.0, 0.0, 0.0) void
display(void) glClear(GL_COLOR_BUFFER_BIT) glCol
or3f (1.0, 1.0, 1.0) glRasterPos2i (20, 20)
//The command glRasterPos() position //a
single bitmap on the screen. //
draw the character F three times on the
screen. glBitmap (10, 12, 0.0, 0.0, 11.0, 0.0,
rasters) // glBitmap() draw a single bitmap on
the screen glBitmap (10, 12, 0.0, 0.0, 11.0,
0.0, rasters) glBitmap (10, 12, 0.0, 0.0, 11.0,
0.0, rasters) glFlush()
back
to return to index
84Bitmaps(IV) Figure 8-1 shows the F as a bitmap
and itscorresponding bitmap data.back
Figure 8-1
back
to return to index
85Bitmaps(V) Choosing a Color for the Bitmap.back
The same glColor() and glIndex() commands are
used to set different state variables,
GL_CURRENT_RASTER_COLOR and GL_CURRENT_RASTER_IN
DEX, for rendering bitmaps. The raster color
state variables are set when glRasterPos()
is called, which can lead to a trap. In the
following sequence of code, the color of the
bitmap is white! glColor3f(1.0, 1.0, 1.0) /
white / glRasterPos3fv(position) glColor3f(1.0,
0.0, 0.0) / red / glBitmap(....) GL_CURRENT_R
ASTER_COLOR is set to white when glRasterPos3fv()
is called. The second call to glColor3f() changes
the value of GL_CURRENT_COLOR for future
geometric rendering, but the color used to render
the bitmap is unchanged.
back
to return to index
869.- Texture Mappingback
- There are many possibilities for texture mapping
- map textures to surfaces made of a set of
polygons or to - curved surfaces,
- repeat a texture in one or both directions to
cover the surface. - A texture can even be one-dimensional.
- automatically map a texture onto an object in
such a way that the texture indicates contours or
other properties of the item being viewed. - Shiny objects can be textured so that they
appear to be in the - center of a room or other environment, reflecting
the surroundings off their surfaces. - A texture can be applied to a surface in
different ways - painted on directly (like a decal placed on a
surface), - used to modulate the color the surface would
have been painted otherwise, - or used to blend a texture color with the
surface color.
to return to index
back
879.1.- Organigrama de uso de texturasback
Atar un nombre de textura con un objetivo
(target). Hay 3 opciones para objetivos de
dimensión 1, 2, o 3. En cada instante con cada de
los tres puede ser atada una sola textura. Al
atar otra con el mismo objetivo, se cancela el
atamiento anterior.
Configurar Target como el mapeo de un objerto de
Texture Memory a la pantalla
Determinar el mapeo de textura a un primitivo de
OpenGl
Specificar textura definir la relación (mapeo)
entre una estructura de datos en Processor Memory
y su interpretación en Texture Memory
Configurar entorno de aplicación de textura
Generar nombres para texturas
Sentido funcional
glBindTextures()
glGenTextures()
glTexImage()
glTexParameter()
glTexEnv()
Soporte mediante las Funciones OpenGL
glTexCoord()
Target GL_TEXTURE_1D GL_TEXTURE_2D
GL_TEXTURE_3D
El modo como se interactuan los colores de
engomado (la textura) con los colores del objeto
al cual lo pegamos
Nombre de textura valor entero
Contenido de Texture Memory
estructura de datos en Processor Memory
Objetos que se definen
Primitivo de OpenGL
to return to index
back
88Texture Mapping (II)back
- Steps in Texture Mapping
- To use texture mapping, you perform these steps.
- Create a texture object and specify a texture for
that object. - 2. Indicate how the texture is to be applied to
each pixel. - 3. Enable texture mapping.
- 4. Draw the scene, supplying both texture and
geometric coordinates.
back
to return to index
89Texture Mapping (III)(Naming a texture object )
back
Naming A Texture Object Any nonzero unsigned
integer may be used as a texture name. To avoid
accident