A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

Introdução à Computação Gráfica Texturas

Apresentações semelhantes


Apresentação em tema: "Introdução à Computação Gráfica Texturas"— Transcrição da apresentação:

1 Introdução à Computação Gráfica Texturas
Claudio Esperança Paulo Roma Cavalcanti

2 Detalhes de Superfícies
Modelos de iluminação não são apropriados para descrever todas as diferenças de cor observáveis em uma superfície Superfícies pintadas com padrões ou imagens A capa ou uma página de um livro Superfícies com padrões de rugosidade Tecidos ou uma parede de tijolos Em princípio é possível modelar esses detalhes com geometria e usando materiais de propriedades óticas distintas Na prática, esses efeitos são modelados usando uma técnica chamada mapeamento de textura

3 Mapeamento de Textura A idéia é reproduzir sobre a superfície de algum objeto da cena as propriedades de alguma função – ou mapa - bidimensional (cor, por exemplo)

4 Propriedades Mapeáveis
Quais parâmetros ou propriedades pode-se reproduzir a partir de mapas: Cor (coeficientes de reflexão difusa) Coeficientes de reflexão especular e difusa Mapeamento de ambiente Perturbação do vetor normal “Bump Mapping” Perturbação da superfície na direção da normal “Displacement Mapping” Transparência / opacidade

5 Espaço de Textura Texturas 2D são funções T (s, t) cujo domínio é um espaço bidimensional e o contradomínio pode ser cor, opacidade, etc É comum ajustar a escala da imagem de tal forma que a imagem toda se enquadre no intervalo 0 ≤ s, t ≤ 1 Normalmente a função em si é derivada de alguma imagem capturada Se a imagem está armazenada numa matriz Im [0..N–1 , 0..M–1] Então T (s, t) = Im [ (1 – t) N , s M ] t 1 1 s

6 Espaço de Textura Pode ser vantajoso assumir que o padrão da imagem se repete fora desse intervalo T (s, t) = Im [ (1 – t) N mod N, s M mod M ] A função de textura pode ser também definida algebricamente:

7 Função de Mapeamento Retorna o ponto do objeto correspondente a cada ponto do espaço de textura (x, y, z) = F (s, t) Corresponde à forma com que a textura é usada para “embrulhar” (wrap) o objeto Na verdade, na maioria dos casos, precisamos de uma função que nos permita “desembrulhar” (unwrap) a textura do objeto, isto é, a inversa da função de mapeamento Se a superfície do objeto pode ser descrita em forma paramétrica esta pode servir como base para a função de mapeamento

8 Parametrização da Esfera
Função de mapeamento z φ y Função de mapeamento inversa x

9 Parametrização do Cilindro
Função de mapeamento z y Função de mapeamento inversa x

10 Parametrizando Objetos Genéricos
O que fazer quando o objeto não comporta uma parametrização natural? Uma sugestão é usar um mapeamento em 2 estágios [Bier e Sloan]: Mapear textura sobre uma superfície simples como cilindro, esfera, etc aproximadamente englobando o objeto Mapear superfície simples sobre a superfície do objeto. Pode ser feito de diversas maneiras Raios passando pelo centróide do objeto Raios normais à superfície do objeto Raios normais à superfície simples Raios refletidos (environment mapping)

11 Exemplos Parametrização cúbica Projetada em um cilindro
Projetada em uma esfera

12 Exemplos Projetada em um cubo Parametrização cilíndrica
Projetada em uma esfera

13 Parametrização esférica
Exemplos Projetada em um cilindro Parametrização esférica Projetada em um cubo

14 Processo de Mapeamento de Texturas
Projeção do pixel sobre a superfície Pontos da superfície correspondentes aos vértices do pixel Parametrização Coordenadas paramétricas dos vértices do pixel projetados Mapeamento inverso Coordenadas dos vértices no espaço de textura Média Cor média dos ‘Texels’ proporcional à àrea coberta pelo quadrilátero u v i j s t

15 Mapeamento de Texturas em Polígonos
Polígonos são freqüentemente usados para representar fronteiras de objetos Em OpenGL, além das coordenadas dos vértices e do vetor normal, é possível também especificar coordenadas de textura: glBegin (GL_POLYGON); glNormal3fv (N); glTexCoord2fv (T); glVertex3fv (V); ... glEnd ();

16 Mapeamento de Texturas em Polígonos
A maneira mais simples e rápida: Projetar os vértices do polígono na imagem A cada vértice projetado Pi corresponde um ponto Qi no espaço de textura Um pixel P do polígono na imagem é dado por uma combinação afim. Ex.: P = 1P1 + 2P2 + 3P3 Pixel P é pintado com a cor do texel obtido com a mesma combinação afim. Ex.: Q = 1Q1 + 2Q2 + 3Q3

17 Mapeamento de Texturas em Polígonos
Problemas da abordagem simples: Aliasing Pixel <≠> Texel Soluções: Interpolação Mip-mapping Deformação Combinações afim não são preservadas em projeções perspectivas Mais vértices Coordenadas homogêneas

18 Mapeamento de Texturas em OpenGL
Ligar o mapeamento de texturas glEnable(GL_TEXTURE_2D); Especificar a textura Usar glTexImage2D que tem o formato void glTexImage2D (GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); Exemplo: glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 128, 128, 0, GL_RGBA, GL_UNSIGNED_BYTE, img);

19 Mapeamento de Texturas em OpenGL
Configurar diversos parâmetros Modos de filtragem Magnificação ou minificação Filtros mipmap de minificação Modos de repetição de padrões Cortar ou repetir Funções de aplicação de textura Como misturar a cor do objeto com a da textura Misturar, modular ou substituir texels Especificar coordenadas de textura Por vértice glTexCoord* Coordenadas computadas autometicamente glTexGen*

20 Especificando imagem de textura
CPU DL Poly. Per Vertex Raster Frag FB Pixel Texture Imagem de textura normalmente carregada a partir de um array de texels na memória principal glTexImage2D( target, level, components, w, h, border, format, type, *texels ); Tamanho da imagem tem ser potência de 2 Cores dos texels são processadas pela parte do pipeline que processa pixels Boa parte do repertório de operações sobre bitmaps pode ser usada Specifying the texels for a texture is done using the glTexImage{123}D() call. This will transfer the texels in CPU memory to OpenGL, where they will be processed and converted into an internal format. The array of texels sent to OpenGL with glTexImage*() must be a power of two in both directions. An optional one texel wide border may be added around the image. This is useful for certain wrapping modes. The level parameter is used for defining how OpenGL should use this image when mapping texels to pixels. Generally, you’ll set the level to 0, unless you’re using a texturing technique called mipmapping, which we’ll discuss in a few slides.

21 Convertendo Imagem de Textura
Se o tamanho da imagem não é uma potencia de 2 gluScaleImage( format, w_in, h_in, type_in, *data_in, w_out, h_out, type_out, *data_out ); *_in = imagem original *_out = imagem destino Imagem é interpolada e filtrada durante a escala If your image does not meet the power of two requirement for a dimension, the gluScaleImage() call will resample an image to a particular size. It uses a simple box filter to interpolate the new images pixels from the source image. Additionally, gluScaleImage() can be used to convert from one data type ( i.e. GL_FLOAT ) to another type, which may better match the internal format in which OpenGL stores your texture. Note that use of gluScaleImage() can also save memory.

22 Outros métodos para especificar texturas
Usar o frame buffer como fonte da imagem de textura glCopyTexImage1D(...) glCopyTexImage2D(...) Modificar parte de uma textura pré-definida glTexSubImage1D(...) glTexSubImage2D(...) glTexSubImage3D(...) glCopyTexImage*() allows textures to be defined by rendering into any of OpenGL’s buffers. The source buffer is selected using the glReadBuffer() command. Using glTexSubImage*() to replace all or part of an existing texture often outperforms using glTexImage*() to allocate and define a new one. This can be useful for creating a “texture movie” ( sequence of textures which changes appearance on an object’s surface ). There are some advanced techniques using glTexSubImage*() which include loading an image which doesn’t meet the power of two requirement. Additionally, several small images can be “packed” into one larger image ( which was originally created with glTexImage*() ), and loaded individually with glTexSubImage*(). Both of these techniques require the manipulation of the texture transform matrix, which is outside the scope of this course.

23 Mapeando a Textura Baseado em coordenadas paramétricas de textura
CPU DL Poly. Per Vertex Raster Frag FB Pixel Texture Baseado em coordenadas paramétricas de textura Chamar glTexCoord*() para cada vértice Espaço de Textura Espaço do Objeto t 1, 1 (s, t) = (0.2, 0.8) 0, 1 A a When you want to map a texture onto a geometric primitive, you need to provide texture coordinates. The glTexCoord*() call sets the current texture coordinates. Valid texture coordinates are between 0 and 1, for each texture dimension, and the default texture coordinate is ( 0, 0, 0, 1 ). If you pass fewer texture coordinates than the currently active texture mode ( for example, using glTexCoord1d() while GL_TEXTURE_2D is enabled ), the additionally required texture coordinates take on default values. c (0.4, 0.2) b B C (0.8, 0.4) 0, 0 1, 0 s

24 Gerando Coordenadas de Texturas Automaticamente
Habilitar a geração automatica de coordenadas de textura glEnable (GL_TEXTURE_GEN_{STRQ}); Especificar parâmetros void glTexGen{ifd} (GLenum coord, GLenum pname, TYPE param); void glTexGen{ifd}v (GLenum coord, GLenum pname, TYPE *param); Qual coordenada de textura? Coord = GL_S / GL_T / GL_R / GL_Q Plano de referência Pname = GL_OBJECT_PLANE / GL_EYE_PLANE Param = coeficientes A/B/C/D do plano Modos de geração de coordenadas Pname = GL_TEXTURE_GEN_MODE Param = GL_OBJECT_LINEAR / GL_EYE_LINEAR / GL_SPHERE_MAP You can have OpenGL automatically generate texture coordinates for vertices by using the glTexGen() and glEnable(GL_TEXTURE_GEN_{STRQ}). The coordinates are computed by determining the vertex’s distance from each of the enabled generation planes. As with lighting positions, texture generation planes are transformed by the ModelView matrix, which allows different results based upon when the glTexGen() is issued. There are three ways in which texture coordinates are generated: GL_OBJECT_LINEAR - textures are fixed to the object ( like wall paper ) GL_EYE_LINEAR - texture fixed in space, and object move through texture ( like underwater light shining on a swimming fish) GL_SPHERE_MAP - object reflects environment, as if it were made of mirrors (like the shiny guy in Terminator 2)

25 Geração Automática de Coordenadas de Textura
GL_EYE_LINEAR

26 Geração Automática de Coordenadas de Textura
GL_OBJECT_LINEAR

27 Filtragem Exemplo: glTexParameteri( target, type, mode ); Textura
GL_NEAREST GL_LINEAR GL_NEAREST_MIPMAP_NEAREST GL_NEAREST_MIPMAP_LINEAR GL_LINEAR_MIPMAP_NEAREST GL_LINEAR_MIPMAP_LINEAR GL_TEXTURE_2D GL_TEXTURE_1D GL_TEXTURE_MAG_FILTER GL_TEXTURE_MIN_FILTER Exemplo: glTexParameteri( target, type, mode ); Textura Polígono Magnificação Minificação Polígono Textura Filter modes control how pixels are minified or magnified. Generally a color is computed using the nearest texel or by a linear average of several texels. The filter type, above is one of GL_TEXTURE_MIN_FILTER or GL_TEXTURE_MAG_FILTER. The mode is one of GL_NEAREST, GL_LINEAR, or special modes for mipmapping. Mipmapping modes are used for minification only, and have values of: GL_NEAREST_MIPMAP_NEAREST GL_NEAREST_MIPMAP_LINEAR GL_LINEAR_MIPMAP_NEAREST GL_LINEAR_MIPMAP_LINEAR Full coverage of mipmap texture filters is outside the scope of this course.

28 Imagens minificadas pré-filtradas
Texturas Mipmap Textura original Imagens minificadas pré-filtradas As primitives become smaller in screen space, a texture may appear to shimmer as the minification filters creates rougher approximations. Mipmapping is an attempt to reduce the shimmer effect by creating several approximations of the original image at lower resolutions. Each mipmap level should have an image which is one-half the height and width of the previous level, to a minimum of one texel in either dimension. For example, level 0 could be 32 x 8 texels. Then level 1 would be 16 x 4; level 2 would be 8 x 2; level 3, 4 x 1; level 4, 2 x 1, and finally, level 5, 1 x 1. The gluBuild*Dmipmaps() routines will automatically generate each mipmap image, and call glTexImage*D() with the appropriate level value. OpenGL 1.2 introduces control over the minimum and maximum mipmap levels, so you don’t have to specify every mipmap level (and also add more levels, on the fly).

29 Texturas Mipmap Permite que texturas de diferentes níveis de resolução sejam aplicadas de forma adaptativa Reduz aliasing devido a problemas de interpolação O nível da textura na hierarquia mipmap é especificada durante a definição da textura glTexImage*D( GL_TEXTURE_*D, level, … ) GLU possui rotinas auxiliares para construir texturas mipmap com filtragem adequada gluBuild*DMipmaps( … ) OpenGL 1.2 suporta facilidades mais sofisticadas para níveis de detalhe (LOD) As primitives become smaller in screen space, a texture may appear to shimmer as the minification filters creates rougher approximations. Mipmapping is an attempt to reduce the shimmer effect by creating several approximations of the original image at lower resolutions. Each mipmap level should have an image which is one-half the height and width of the previous level, to a minimum of one texel in either dimension. For example, level 0 could be 32 x 8 texels. Then level 1 would be 16 x 4; level 2 would be 8 x 2; level 3, 4 x 1; level 4, 2 x 1, and finally, level 5, 1 x 1. The gluBuild*Dmipmaps() routines will automatically generate each mipmap image, and call glTexImage*D() with the appropriate level value. OpenGL 1.2 introduces control over the minimum and maximum mipmap levels, so you don’t have to specify every mipmap level (and also add more levels, on the fly).

30 Modos de Repetição Exemplo:
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ) Wrap mode determines what should happen if a texture coordinate lies outside of the [0,1] range. If the GL_REPEAT wrap mode is used, for texture coordinate values less than zero or greater than one, the integer is ignored and only the fractional value is used. If the GL_CLAMP wrap mode is used, the texture value at the extreme (either 0 or 1) is used. textura s t GL_CLAMP GL_REPEAT

31 Modos de Aplicação de Textura
Controla como a cor da textura afeta a cor do pixel glTexEnv{fi}[v](GL_TEXTURE_ENV, prop, param ) Modos (prop = TEXTURE_ENV_MODE) GL_MODULATE GL_BLEND GL_REPLACE Cor a ser misturada (GL_BLEND) Especificada com prop = GL_TEXTURE_ENV_COLOR The texture mode determines how texels and fragment colors are combined. The most common modes are: GL_MODULATE - multiply texel and fragment color GL_BLEND - linearly blend texel, fragment, env color GL_REPLACE - replace fragment’s color with texel If prop is GL_TEXTURE_ENV_COLOR, param is an array of four floating point values representing the color to be used with the GL_BLEND texture function.

32 glHint( GL_PERSPECTIVE_CORRECTION_HINT, hint )
Correção Perspectiva Mapeamento de texturas em polígonos pode ser feito: Da forma simples e rápida (interpolação linear) Usando interpolação em coordenadas homogêneas Comportamento do OpenGL é influenciado por “dicas” (“hints”) glHint( GL_PERSPECTIVE_CORRECTION_HINT, hint ) onde hint pode ser GL_DONT_CARE GL_NICEST GL_FASTEST O OpenGL não necessariamente obedece! An OpenGL implementation may chose to ignore hints.

33 Outras Facilidades Objetos de Textura (Texture Objects)
Permite mudar rapidamente de texturas durante a renderização de diversos objetos Controle de espaço na memória de texturas Texturas residentes na placa são mais rápidas Multitexturas (Extensões OpenGL) Placas + modernas (NVidia GeForce /ATI Radeon) Mais de uma textura mapeada no mesmo objeto Permite uma série de efeitos interessantes Shadow mapping Bump mapping


Carregar ppt "Introdução à Computação Gráfica Texturas"

Apresentações semelhantes


Anúncios Google