Documentos de Académico
Documentos de Profesional
Documentos de Cultura
ndice
Introduccin
Qu son las 3D? Matemticas de las 3D API's de bajo nivel
Introduccin a OpenGL
Qu se necesita? Formato de las funciones Matrices y Buffers Inicializacin del entorno Nuestro primer programa con 3D
Primitivas grficas
Tringulos Polgonos
5 de abril de 2005
ndice
Transformaciones
Bsicas Complejas
Texturas
Qu son? Uso de texturas
Luces
Uso de la luz
5 de abril de 2005
ndice
OpenGL avanzado API's de alto nivel Enlaces
5 de abril de 2005
Introduccin
Introduccin
Qu son las 3D?
La capacidad de representar imgenes realistas en una superficie plana (2D) til para efectos especiales, videojuegos, industria qumica, simulacin, etc.
5 de abril de 2005
Introduccin
Matemticas de las 3D
Cmo pasar de 3D a 2D? v = x , y , z p=
Este mtodo no puede ser utilizado con matrices. El uso de matrices es ms cmodo y permite generalizarlo para otros usos.
v ' = x , y , z , w p ' = x , y ,0 , t Si v ' = x , y , z , w v = x / w , y / w , z / w Si p ' = x , y ,0 , t p = x / t , y / t t =1 z / d
Samuel Rodrguez Sevilla (GUL UC3M) OpenGL: Programacin de juegos en 3D 5 de abril de 2005 7
x y , 1 z / d 1 z / d
Introduccin
Matemticas de las 3D
Cmo pasar de 3D a 2D? 1 0 P= 0 0
0 0 1 0 0 0 0 1 / d
0 0 0 1
x y p ' =P =P v' z w
[]
]
5 de abril de 2005 8
Introduccin
API's de bajo nivel
Una API es un conjunto de funciones que hacen algo conocido, pero no nos dicen como. Son de propsito general. En programacin en 3D las hay de dos tipos: Especficas (como Glide de 3Dfx). Generales (como Direct 3D y OpenGL).
5 de abril de 2005
Introduccin a OpenGL
Introduccin a OpenGL
Qu se necesita?
Se requiere las libreras de desarrollo de OpenGL. En Debian: apt-get intall mesag3 Es recomendable, tambin, disponer de SDL: apt-get install libsdl1.2-dev Es obligatorio un compilador de C/C++. En la prctica, OpenGL est soportado por muchos lenguajes de programacin: C/C++, java, python, perl, pascal, delphi, todos los de .Net (C#, VB.Net, etc.) ...
5 de abril de 2005
11
Introduccin a OpenGL
Formato de las funciones
glNombrefuncion[numero_parametros][tipo_parametros]
glVector2i(int, int); glVector3f(float, float, float); glVector4d(double, double, double, double);
5 de abril de 2005
12
Introduccin a OpenGL
Matrices y Buffers
OpenGL hace uso de distintos buffer y matrices para trabajar. Buffers: estarcido, profundidad, resultado, etc. Se activan con glEnable. Matrices: Proyeccin, modelado, etc. Se cambia de una a otra con glMatrixMode. Las matrices pueden ser almacenadas en una pila con glPushMatrix. Para rescatarla, se usa glPopMatrix. La matriz identidad es glLoadIdentity. Para hacer perspectiva, se usa glFrustum (es mejor usar gluPerspective de la librera glu).
Samuel Rodrguez Sevilla (GUL UC3M) OpenGL: Programacin de juegos en 3D 5 de abril de 2005 13
Introduccin a OpenGL
Inicializacin del entorno
OpenGL no entiende qu es una ventana o qu es el modo a pantalla completa. Tampoco sabe cmo inicializar los modos grficos. Por ello, se requiere de una librera a parte que si lo entienda (en Direct 3D, se usa Direct Draw). Utilizaremos SDL por ser multiplataforma.
5 de abril de 2005
14
Introduccin a OpenGL
Inicializacin del entorno
/* This is our SDL surface */ SDL_Surface *surface; /* Flags to pass to SDL_SetVideoMode */ int videoFlags; /* initialize SDL */ if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { fprintf( stderr, "Video initialization failed: %s\n", SDL_GetError( ) ); exit( 1 ); } /* the flags to pass to SDL_SetVideoMode */ videoFlags = SDL_OPENGL; /* Enable OpenGL in SDL */ videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */ videoFlags |= SDL_HWPALETTE; /* Store the palette in hardware */ videoFlags |= SDL_RESIZABLE; /* Enable window resizing */ /* Sets up OpenGL double buffering */ SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); /* get a SDL surface */ surface = SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_BPP,videoFlags); /* Verify there is a surface */ if ( !surface ) { fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) ); exit( 1 ); } Samuel Rodrguez Sevilla (GUL UC3M) OpenGL: Programacin de juegos en 3D 5 de abril de 2005 15
Introduccin a OpenGL
Nuestro primer programa con 3D
/* Enable smooth shading */ glShadeModel( GL_SMOOTH ); /* Set the background black */ glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); /* Depth buffer setup */ glClearDepth( 1.0f ); /* Enables Depth Testing */ glEnable( GL_DEPTH_TEST ); /* The Type Of Depth Test To Do */ glDepthFunc( GL_LEQUAL ); /* Really Nice Perspective Calculations */ glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); /* Height / width ration */ GLfloat ratio; /* Protect against a divide by zero */ if ( height == 0 ) height = 1; ratio = ( GLfloat )width / ( GLfloat )height; /* Setup our viewport. */ glViewport( 0, 0, ( GLsizei )width, ( GLsizei )height );
5 de abril de 2005
16
Introduccin a OpenGL
Nuestro primer programa con 3D
/* change to the projection matrix and set our viewing volume. */ glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); /* Set our perspective */ gluPerspective( 45.0f, ratio, 0.1f, 100.0f ); /* Make sure we're chaning the model view and not the projection */ glMatrixMode( GL_MODELVIEW ); /* Reset The View */ glLoadIdentity( ); /* Clear The Screen And The Depth Buffer */ glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); /* Move Left 1.5 Units And Into The Screen 6.0 */ glLoadIdentity(); glTranslatef( 0.0f, 0.0f, -6.0f ); glBegin( GL_TRIANGLES ); /* Drawing Using Triangles */ glVertex3f( 0.0f, 1.0f, 0.0f ); /* Top */ glVertex3f( -1.0f, -1.0f, 0.0f ); /* Bottom Left */ glVertex3f( 1.0f, -1.0f, 0.0f ); /* Bottom Right */ glEnd( ); /* Finished Drawing The Triangle */ /* Draw it to the screen */ SDL_GL_SwapBuffers( );
5 de abril de 2005
17
Primitivas grficas
Primitivas grficas
Tringulos
Es la primitiva ms sencilla. Se compone de tres vrtices.
glBegin( GL_TRIANGLES ); glVertex3f( x1, y1, z1 ); glVertex3f( x2, y2, z2 ); glVertex3f( x3, y3, z3 ); glEnd();
5 de abril de 2005
19
Primitivas grficas
Polgonos
Es ms complejo que un tringulo. Internamente se convierte en tringulos. Se compone de tres o ms vrtices.
glBegin( GL_POLYGON ); glVertex3f( x1, y1, z1 ); glVertex3f( x2, y2, z2 ); glVertex3f( x3, y3, z3 ); ... glVertex3f( xn, yn, zn ); glEnd();
Transformaciones
Transformaciones
Bsicas
Las transformaciones son todas aquellas operaciones que nos permiten modificar la forma y la posicin de los elementos en el momento de su procesado. Las transformaciones se almacenan en la matriz de modelado. Hay tres transformaciones bsicas en OpenGL: Rotacin Translacin Escalado Las transformaciones deben realizarse antes que el dibujado.
Samuel Rodrguez Sevilla (GUL UC3M) OpenGL: Programacin de juegos en 3D 5 de abril de 2005 22
Transformaciones
Bsicas
Rotacin Consiste en hacer girar el objeto en pantalla.
glRotatef( angulo, eje_x, eje_y, eje_z )
angulo => ngulo que vamos a girar (en grados) eje_? => vale 0.0f 1.0f. Indica los ejes a los que se aplica la rotacin.
5 de abril de 2005
23
Transformaciones
Bsicas
Translacin Consiste en mover el objeto en pantalla.
glTranslatef( eje_x, eje_y, eje_z )
5 de abril de 2005
24
Transformaciones
Bsicas
Escalado Consiste en cambiar el tamao del objeto.
glScalef( eje_x, eje_y, eje_z )
5 de abril de 2005
25
Transformaciones
Complejas
Una transformacin compleja es aquella que es unin de dos o ms simples. Puede ser una transformacin propia (que no sea de traslacin, rotacin ni escalado). Cuando se aplica una transformacin, se hace el producto de la matriz de modelado y la transformacin, por ello, el orden de aplicacin es muy importante.
5 de abril de 2005
26
Transformaciones
Complejas
Translacin+Rotacin
Rotacin+Translacin
5 de abril de 2005
27
Transformaciones
Complejas
Transformaciones propias Debemos crear una matriz con los valores de la transformacin.
Glfloat Matriz[4][4]; /* Rellenamos con los valores */ Matrix[0][0] = ....; /* Cargamos la matriz */ glMultMatrixf( Matrix );
5 de abril de 2005
28
Texturas
Texturas
Qu son?
Imgenes que se colocan sobre los polgonos. Dan realismo al los objetos. Deben tener dimensiones potencia de 2 (2, 4, 8, 16, 32, 64, ...). *En OpenGL 2.0 esta necesidad desaparece. Las imgenes deben ser cargadas previamente. Es recomendable usar SDL_image.
5 de abril de 2005
30
Texturas
Uso de texturas
Para guardar la textura en la memoria de vdeo:
glNewList( idTextura=glGenList(1), GL_COMPILE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glPixelStorei(GL_UNPACK_ALIGMENT, 4); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); glPixelStorei(GL_UNPACK_SKIP_PIXES, 0); glTexImage2D(GL_TEXTURE_2D, 0, 3, imagen->w,i magen->h, 0, GL_RGB, GL_UNSIGNED_BYTE, imagen->pixels ); glEndList();
Samuel Rodrguez Sevilla (GUL UC3M) OpenGL: Programacin de juegos en 3D 5 de abril de 2005 31
Texturas
Uso de texturas
Para activar el uso de la textura:
glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
Luces
Luces
Uso de la luz
Activar la iluminacin
glEnable(GL_LIGHTING);
5 de abril de 2005
34
Luces
Uso de la luz
Hacer que los polgonos reflejen la luz
glEnable(GL_COLOR_MATERIAL); glColorMaterial(CARA, MODO_EN_QUE_AFECTA);
5 de abril de 2005
35
OpenGL avanzado
OpenGL avanzado
Extensiones
Mecanismo de OpenGL para aadir funcionalidades que no se encontraban en el estandar: texturas que no tienen porque ser potencia de dos, nieblas volumtricas, etc. GLSL: OpenGL Sharing Language Lenguaje de programacin que genera binarios que son cargados directamente en la aceleradora grfica. Permiten hacer muchos efectos especiales.
5 de abril de 2005
37
5 de abril de 2005
39
Enlaces
Enlaces
http://www.opengl.org/ http://nehe.gamedev.net/ http://www.ultimategameprogramming.com/ http://www.humus.ca/
5 de abril de 2005
41