You are on page 1of 9

Introducción

• Sistema gráfico :
Librerías Gráficas – Modelos + Visualización
Introducción a OpenGL • Visualización:
– Uso de hardware específico (2D o 3D)
– Implementación a través de librerías

Definición de librería gráfica Librerías, ficheros, sintaxis


• Software que genera imágenes en base a unos • Origen
modelos matemáticos y unos patrones de – IGL-Plot 10 (Tektronix)
– Starbase (Hewlett Packard)
iluminación, texturas, etc. – Iris GL Library (SGI)

• Distinguir la naturaleza de otros sistemas


gráficos
– VRML, X3D (Lenguajes de descripción)
– DirectX-Direct3D
– Java 3D
– Open Inventor
– Performer, Fahrenheit
– Motores

Objetivos de las librerías gráficas Tipos de librerías gráficas


• Independencia del hardware (tanto • Direct Rendering and gfx packages:
dispositivos de entrada como de salida). – OpenGL, Direct3D, GKS, PHIGS, PEX, GKS, etc…

• Independencia de la aplicación (la librería • Scene-graph based


– OpenGL Performer, Open Inventor, OpenGL Optimizer,
es accedida a través de un interface único PHIGS+, etc…
(al menos para cada lenguaje de • Toolkits
programación) para cualquier aplicación. – World Toolkit, AVANGO, Game Engines, etc…

1
... ...
• Gestión imágenes 3D • (... Gestión imágenes 3D)
– “Bajo nivel” – “ Alto nivel”
• Tareas • Tareas
– Gestión “en serie” de los elementos de la escena – Gestión global de los elementos de la escena
– Elementos de la escena – Árbol escena
» Primitivas gráficas – Carga/descarga de memoria
» “Atributos” (" edición imágenes) – Gestión elementos no visibles
– Variables de estado – Elección del modelo geométrico: Nivel detalle, Textura
Generación imagen – Elección de la técnica de presentación (rendering)
• Sistemas • Sistemas
– OpenGL – Inventor
– Direct 3D – Performer
– Java 3D – ( Fahrenheit )
– “ Alto nivel” … – Hewlett Packard

DirectX Componentes DirectX - Introducción


• DirectDraw • ¿Qué es DirectX?
• DirectSound – Conjunto de API´s que permite a los
desarrolladores de contenido interactivo
• DirectPlay
(imagen, video, sonido...) acceder a
• Direct3D características de hardware especializado sin
• .... tener que escribir código específico de
hardware

DirectX - Introducción
DirectX - Introducción • Objetivos de DirectX
– Desarrollo de Aplicaciones Windows de alto
• Componentes incluidos en DirectX rendimiento
– Nos permiten desarrollar aplicaciones de alto • Tarjetas aceleradoras
rendimiento y en tiempo real • Plug´n Play
• API Direct Play • Servicios de comunicaciones construidos bajo
• API Direct I nput Windows
• API Direct Sound • Recursos instalados en el sistema
• API Direct Draw – Utilización del nuevo hardware implementado
• API Direct 3D

2
DirectX - Introducción
• DirectX & COM (Component Object DirectX - DirectDraw
Model)
• Obj et o: caja negra que representa el hardware y
• Se encarga del manejo de la memoria de vídeo
requiere comunicación con las aplicaciones a través • Proporciona herramientas para
de una interface. – Manipulación de múltiples buffers de vídeo
• Mét odo: comandos enviados y recibidos por el – Acceso directo a la memoria de vídeo
objeto a través de la interface COM – Page flipping
– Ej.: Método Get DisplayMode es enviado a – Back Buffering
través de la interface I Direct Draw2 para – Manejo de la paleta gráfica
tomar el valor de la actual resolución de la – Clipping
pantalla mediante el objeto Direct Draw

DirectX - DirectDraw
DirectX - DirectDraw
• Conceptos Gráficos y Técnicos
– Bitmaps
• Tipos de objetos – Superficies de dibujo (buffers)
– I Direct Draw – Page Flipping y Back Buffering
– I Direct DrawSurf ace – Rectángulos
– Sprites
– I Direct DrawPalet t e
– Niveles cooperativos
– I Direct DrawClipper – Modos de vídeo
– I Direct DrawVideoPort – Buffers
– Overlays
– Clippers
– Video Ports

DirectX - DirectSound DirectX - DirectSound


• Componente de Audio de DirectX: • Interfaces COM
– Mezclado de canales de audio – I Direct SoundBuf f er
– Aceleración hardware – I Direct Sound3DBuf f er
– Acceso directo al dispositivo de sonido – I Direct Sound3DList ener
– Captura de Audio – I Direct SoundCapt ure
– I Direct SoundCapt ureBuf f er

3
DirectX - Direct3D
DirectX - DirectPlay • Interfaz gráfica para hardware 3D
• Simplifica el acceso de las aplicaciones a
– Permitir gráficos tridimensionales interactivos
los servicios de comunicación en aplicaciones de Windows
• Otorga independencia para la creación de • 2 Modos:
servidores de juegos – Inmediato
• Comunicaciones • API 3D de bajo nivel
– Peer-to-Peer • Independiente del dispositivo
– Cliente/Servidor • Programadores experimentados
– Retenido (Obsoleta)
• Desarrollo rápidos
• Capa superior del inmediato

DirectX - Direct3D DirectX - Direct3D


• Conceptos Básicos • Conceptos Básicos
– Sistemas de coordenadas 3-D – Triángulos
• Left-handed (mano izquierda)
– Reglas de rasterización de triángulos
• Podemos simular el right-handed
– Transformaciones 3-D
• Traslación
• Rotación
• Escalado
– Polígonos
• Normales de cara y vértice
• Modos de sombreado
• Interpolaciones de triángulos

OpenGL Objetivos de diseño de OpenGL:


• Introducido en 1992 por SGI • API gráfico de altas prestaciones (con
• Basado en IRIS GL, un API para aceleración por hardware)
workstations SGI • Posee cierta independencia del hardware
• Es un open standard que ha sido adoptado • Es un API natural (en C) con posibilidad de
ampliamente para todo tipo de aplicaciones
gráficas extensibilidad
• Se desarrolla bajo la supervisión del
OpenGL architecture review board

4
Se convierte en standard porque …
Ventajas de OpenGL
• Industry standard
An independent consortium, the OpenGL Architecture Review Board, guides
the OpenGL specification. With broad industry support, OpenGL is the only
• No trata de hacer demasiadas cosas: truly open, vendor-neutral, multiplatform graphics standard.
– Sólo renderiza la imagen, no gestiona ventanas, etc... • Stable
OpenGL implementations have been available for more than seven years on
– No posee animación de alto nivel, modelado, sonido, a wide variety of platforms. Additions to the specification are well controlled,
etc... and proposed updates are announced in time for developers to adopt changes.
Backward compatibility requirements ensure that existing applications do not
• Hace lo suficiente: become obsolete.
• Reliable and portable
– Efectos de renderizado útiles y altas prestaciones All OpenGL applications produce consistent visual display results on any
OpenGL API-compliant hardware, regardless of operating system or
• Fue promovido por empresas líderes en el sector windowing system.
(SGI, Microsoft, etc)

Ventajas de OpenGL Ventajas de OpenGL


• Evolving • Easy to use
Because of its thorough and forward-looking design, OpenGL allows new OpenGL is well structured with an intuitive design and logical commands.
hardware innovations to be accessible through the API via the OpenGL Efficient OpenGL routines typically result in applications with fewer lines of
extension mechanism. In this way, innovations appear in the API in a timely code than those that make up programs generated using other graphics
fashion, letting application developers and hardware vendors incorporate new libraries or packages. In addition, OpenGL drivers encapsulate information
features into their normal product release cycles. about the underlying hardware, freeing the application developer from having
• Scalable to design for specific hardware features.
OpenGL API-based applications can run on systems ranging from consumer • Well-documented
electronics to PCs, workstations, and supercomputers. As a result, Numerous books have been published about OpenGL, and a great deal of
applications can scale to any class of machine that the developer chooses to sample code is readily available, making information about OpenGL
target. inexpensive and easy to obtain.

Renderizado de OpenGL Arquitectura OpenGL


• Primitivas geométricas:
– Puntos, líneas y polígonos
• Primitivas de imágenes:
– Imágenes y bitmaps
• Pipelines separados para imágenes y geometría
unidos mediante el mapeador de texturas
• El renderizado depende del estado (luces, colores,
materiales, etc)

5
Capacidades de OpenGL Capacidades de OpenGL
• Accumulation buffer A buffer in which multiple rendered frames can • Double buffering. Used to provide smooth animation of objects. Each
be composited to produce a single blended image. Used for effects successive scene of an object in motion can be constructed in the back
such as depth of field, motion blur, and full-scene anti-aliasing. or "hidden" buffer and then displayed. This allows only complete
• Alpha blending. Provides a means to create transparent objects. images to ever be displayed on the screen.
• Automatic rescaling of vertex normals changed by the modeling • Feedback. A mode where OpenGL will return the processed geometric
matrix. information (colors, pixel positions, and so on) to the application as
• BGRA pixel formats and packed pixel formats to directly support compared to rendering them into the frame buffer.
more external file and hardware frame buffer types. • Level of detail control for mipmap textures to allow loading only a
• Color-index mode. Color buffers store color indices rather than red, subset of levels.
green, blue, and alpha color components. • Materials lighting and shading. The ability to accurately compute the
• Immediate mode. Execution of OpenGL commands when they're color of any point given the material properties for the surface.
called, rather than from a display list. • Pixel operations. Storing, transforming, mapping, zooming.
• Display list. A named list of OpenGL commands. The contents of a • Polynomial evaluators. To support non-uniform rational B-splines
display list may be preprocessed and might therefore execute more (NURBS).
efficiently than the same set of OpenGL commands executed in • Primitives. A point, line, polygon, bitmap, or image.
immediate mode. • Raster primitives. Bitmaps and pixel rectangles.

Capacidades de OpenGL Capacidades de OpenGL


• RGBA mode. Color buffers store red, green, blue, and alpha color • Texture mapping. The process of applying an image to a graphics
components, rather than indices. primitive. This technique is used to generate realism in images.
• Selection and picking. A mode in which OpenGL determines whether • Three Dimensional Texturing. Three-dimensional texturing for
certain user-identified graphics primitives are rendered into a region of supporting hardware-accelerated volume rendering.
interest in the frame buffer. • Transformation. The ability to change the rotation, size, and
• Specular Highlights. Application of specular highlights after texturing perspective of an object in 3D coordinate space.
for more realistic lighting effects. • Vertex array enhancements to specify a subrange of the array and
• Stencil planes. A buffer used to mask individual pixels in the color draw geometry from that subrange in one operation.
frame buffer. • Z-buffering. The Z-buffer is used to keep track of whether one part of
• Texture coordinate edge clamping to avoid blending border and image an object is closer to the viewer than another.
texels during texturing.

APIs relacionadas APIs de OpenGL


• GLX, WGL, AGX • Librería de funciones para generar imágenes a partir de
– Conexiones de OpenGL con el entorno de ventanas modelos 3D, más otras librerías auxiliares
– gl la librería opengl relacionada directamente con el H/W
• GLU (OpenGL Utility library)
– glu librería de mayor nivel construida sobre opengl
– Es parte de OpenGL
– glaux librería fuera de uso
– Incluye soporte para cuádricas, NURBS, etc. – glut librería para crear interfaces de usuario transportables (Linux,
• GLUT (OpenGL Utility Toolkit) Windows, Unix en general, MacOS)
– No forma parte oficialmente de OpenGL • glut.dll windows\system(32)


• glut.lib DevStudio\Vc\lib
– Permite la portabilidad de las aplicaciones sobre 

• glut.h DevStudio\Vc\include\gl
distintos sistemas de ventanas 

• MESA: OpenGL clone

6
Arquitectura de APIs de OpenGL Detalles de programación
• Añadir las librerías opengl32.lib glu32.lib
glut32.lib
– Project : settings : link : Object/Library Modules
• Ficheros a incluir
– #include <GL/gl.h>
– #include <GL/glu.h>
– If you are using GLUT for managing your window
manager
• #include <GL/glut.h>
• Note that glut.h includes gl.h, glu.h, and glx.h automatically,
so including all three files is redundant.

Estados Command syntax (functions)


• Máquina de estados • glVertex3fv( ... )
– gl tells that this function belongs to the “ gl” s/w package
– Color de fondo
– 3 is used to indicate three arguments
– Intensidad de luz – f is used to indicate that the arguments are floating point
– Material de dibujo – v indicates that the arguments are in vector format
– Luz encendida o apagada • Number Of Arguments: 2, 3, or 4
– etc – Bi-dimensional version of the command
– 3D or rgb
• Valor o estado – Homogeneous coordinates or rgb+alpha
– glColor*(), glGetFloatv() • Formats
– glEnable(), glDisable(), glIsEnabled() – absence of v indicates scalar format
– v indicates vector format

Tipos variables y constantes


Constantes
• Las equivalencias más habituales aparecen en la
tabla
– Se recomienda definir los argumentos que se pasan a las funciones de
• Ejemplo : GL_COLOR_BUFFER_BIT
OpenGL usando sus tipos predefinidos
• Para Glint unos sistemas pueden usar short, otros long
• Defined constants
• Para Glfloat unos sistemas float otros double – Begin with GL_
Data type
Typical Corresponding
C-Language Type
OpenGL
Type Definition
– Use all capital letters
b 8-bit integer
s 16-bit integer
C-Language Type
OpenGL Type
GLbyte
GLshort
– Use underscores to separate words
i 32-bit integer
f 32-bit floating-point
int or long
float
Glint GLsizei
Glfloat GLclampf • Con frecuencia se realizan operaciones “ or”
d 64-bit floating-point double Gldouble GLclampd
ub 8-bit unsigned integer unsigned char Glubyte GLboolean
us 16-bit unsigned integer unsigned short GLushort
unsigned int or Gluint Glenum
ui 32-bit unsigned integer
unsigned long GLbitfield

7
... (gl) ... (glut)
• pure "output", but lacks connection with display
• Window system independent management
– glClear (command)
– “ window” management
– glClearColor (state) • glutInitDisplayModeg( GLUT_RGB | GLUT_SINGLE );
– glBegin glEnd • glutInitWindowSize( WIDTH, HEIGHT );
– glVertex* (geometry) • glutInitWindowPosition ( 550, 350 );
– glColor* (attribute, state) • glutCreateWindow(“ Basic Draw");
– glFlush, glFinish (command stack & processing) – “ input” : event handling
• similar to : The X Window system, MOTIF, MFF, ...
– (debbuging)
• (event)
– (mapping from modelling coord. to display coordinates) • void Display(void); (callback function)
– (aspect ratio) • glutDisplayFunc( Display ); (binding event & callback)
– (need for a transformation management system) – void Display ( void )
• glutMainLoop(); (dispatching events)

Primitivas
...
• Otras primitivas disponibles
– Objetos (uso auxiliar, no para crear modelos)
– Vertex arrays
– Display lists
– Evaluators, NURBS, etc
• Texto
– No existe primitiva
– Usar texturas, problema aliasing

Atributos Variables de estado


• glPointSize(GLfloat)
• glLineWidth(GLfloat) • Valor de defecto
• glLineStipple(GLint factor, GLushort pattern) • Valor actual
– glEnable( GL_LINE_STIPPLE )
• glPolygonMode( face, mode ) • Gestión en una aplicación o en un módulo
– GL_FRONT GL_BACK GL_FRONT_AND_BACK reutilizable
– GL_POINT GL_LINE GL_FILL – Valor de defecto en una aplicación dada
• glPolygonStipple (enable) “ transparency” – Política de cambios de estado en un módulo de software
• glEdgeFlag* mode Line, splitted concave polygons
• glColor* • glPushAttrib( ored mask ) / glPopAttrib()
• glMaterial* – Permiten salvar grupos de atributos

8
GL_ACCUM_BUFFER_BIT accum-buffer
GL_ALL_ATTRIB_BITS --

Grupos de GL_COLOR_BUFFER_BIT
GL_CURRENT_BIT
color-buffer
current Agrupamiento
atributos
GL_DEPTH_BUFFER_BIT depth-buffer
GL_ENABLE_BIT enable
• Arrays
GL_EVAL_BIT eval
GL_FOG_BIT fog – Evitar pérdidas de tiempo en llamadas a funciones
GL_HINT_BIT
GL_LIGHTING_BIT
hint
lighting
• Display Lists
GL_LINE_BIT line – Ídem
GL_LIST_BIT list
– La información puede está preprocesada
GL_PIXEL_MODE_BIT pixel
GL_POINT_BIT point – Almacenar en el procesador gráfico para aliviar el bus
GL_POLYGON_BIT polygon • Workstations
GL_POLYGON_STIPPLE_BI polygon-stipple
T
• PCs
GL_SCISSOR_BIT scissor
GL_STENCIL_BUFFER_BIT stencil-buffer
GL_TEXTURE_BIT texture
GL_TRANSFORM_BIT transform
GL_VIEWPORT_BIT viewport

Comandos entre : glBegin-glEnd Ejemplo : Window to viewport


Command Purpose of Command Reference

glVertex*() set vertex coordinates Chapter 2


• gl
glColor*() set current color Chapter 5 – glMatrixMode
glIndex*() set current color index Chapter 5
– glLoadIdentity
– viewport
glNormal*() set normal vector coordinates Chapter 2
– glOrtho
glEvalCoord*() generate coordinates Chapter 11
– glGetIntegerv
glCallList(), glCallLists() execute display list(s) Chapter 4 • glut
glTexCoord*() set texture coordinates Chapter 9 – glutReshapeFunc( myNewSize )
• void myNewSize( int w, int h )
glEdgeFlag*() control drawing of edges Chapter 2

glMaterial*() set material properties Chapter 6

Links Interesantes
• ww w.opengl.org Official sit e of
OpenGL
• nehe.gam edev.net NeHe, various
OpenGL t ut orials
• rom ka.dem onews.com Rom ka,
various OpenGL t ut orials
• Nexe.gam edev.net sam e as Nehe
for Dirext X

You might also like