• Nenhum resultado encontrado

Special Effects João Madeiras Pereira Animação e Visualização Tridimensional 2012/2013

N/A
N/A
Protected

Academic year: 2021

Share "Special Effects João Madeiras Pereira Animação e Visualização Tridimensional 2012/2013"

Copied!
70
0
0

Texto

(1)

Special Effects

João Madeiras Pereira

jap@inesc.pt

Animação e Visualização Tridimensional

(2)

Motivação

•  Os Efeitos Especiais (SFX) são uma componente importante de qualquer sistema 3D, hoje em dia.

•  Além de ser agradável à vista, aumentam o realismo da cena.

•  Factor muito importante hoje em dia, a nível de marketing, no mercado dos videojogos.

•  Tudo isto é bonito, mas...

•  Não se deixar levar pelo “Eye-Candy” •  Optimizar, optimizar, optimizar!!

•  Não são só os SFX que vendem o vosso produto! •  Exemplos??!

•  Pacman, Tron, Tétris, Pong, Super Mário Bros I, Sheep...

(3)
(4)

4

Billboards

• Technique that adjusts an

object's orientation so that it "faces" some target, usually the camera

• Always aligned with the Virtual

Camera (position or viewing direction)

• Replace a mesh with a

pre-computed picture of the mesh

• Fast to render: a single textured

polygon versus many

(5)

5

What to use it for?

•  to give the illusion of a 3D object without compromising the polygons budget

•  Scenery

•  Trees, grass, spectators

•  Mesh simplification

•  Replace far-away objects with billboards

•  Non-polygonal objects

(6)

6

Billboard basics

•  A billboard is a textured rectangle •  Texture is static •  Draw billboard

where mesh would have been drawn

(7)

7

Billboard basics

•  Need to remove texture background: avoid

visualization of

fragments colored with background texels

•  Two ways:

•  Masking

(8)

8

Billboards by using Masking

•  Billboard fragments alpha values are 0 or 1

•  Draw billboard fragments with alpha equal to 1

•  OpenGL: Alpha test

void glAlphaFunc (GLenum func, GLclampf ref);

Enumerados: GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, GL_NOTEQUAL

glAlphaFunc (GL_GREATER, 0.0f) glEnable(GL_ALPHA_TEST)

(9)

Billboards with Masking

•  Pros

•  Faster

•  Drawing order independent

•  Cons

•  Hard contours

•  Not easy to build such type of textures with alpha

(10)

10

Billboards with Blending

•  Billboard fragments alpha values between [0, 1]

•  Blending

void glBlendFunc (GLenum sfactor, GLenum dfactor); Enumerados: GL_ZERO, GL_ONE, GL_DST_COLOR,

GL_ONE_MINUS_DST_COLOR GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA...

•  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

(11)

Billboards with Blending

•  Pros

•  Smooth blending between the billboard and the

landscape

•  Translucent objects

•  Pros

•  Slower

•  Need to specify depth order to render the

(12)

Simple Billboards

•  No alignment

(13)

Billboard Alignment

•  Billboard per object

•  Spherical billboarding: no restriction to the orientation of the object

•  Cylindrical billboarding: the rotation of the object is restricted to a vector, usually the positive

direction of the Y axis

•  Symmetric objects

•  Walking navigation

•  When the user flies over the scene the illusion

(14)

Billboard alignment

•  Camera Viewing Direction alignment

(15)

Camera Viewing Direction alignment

•  Build a rotation matrix so that the billboard

LookAt vector is normal to the viewing plane of the camera

(16)

ModelView matrix manipulation

•  Setting the 3x3 submatrix to the identity matrix: reverses the scaling and rotation operations

•  The top 3 values of the rightmost column provide the current position of the local origin of the

billboard relative to the camera´s position

•  Spehrical billboarding

☺No orientation calculations

☻ no restriction to the orientation of the object (lying tree, for instance)

(17)

ModelView matrix manipulation

•  float modelview[16];!

•  int i,j;!

•  // save the current modelview matrix!

•  glPushMatrix();!

•  // get the current modelview matrix!

•  glGetFloatv(GL_MODELVIEW_MATRIX , modelview);!

•  // undo all rotations!

•  // beware all scaling is lost as well!

•  for( i=0; i<3; i++ )!

•  for( j=0; j<3; j++ ) {! •  if ( i==j )! •  modelview[i*4+j] = 1.0;! •  else! •  modelview[i*4+j] = 0.0;! •  }!

•  // set the modelview with no rotations and scaling!

•  glLoadMatrixf(modelview);!

•  drawObject();!

•  // restores the modelview matrix!

•  glPopMatrix();!

(18)

Camera Viewing Direction alignment

•  Billboard remains steady with a linear movement of the camera

•  It rotates only with camera rotations

(19)

Camera Position alignment

•  Billboard oriented so that its normal points toward the camera position

(20)

Camera Position alignment

• objToCam = CamPos – ObjPos

• Calculate objToCamProj (set Y component of objToCam to zero) • normalize(objToCamProj)

•  angleCosine = innerProduct(lookAt,objToCamProj) • But cos(angle)=cos(-angle)

• ·upAux = crossProduct(lookAt,objToCamProj) – if positive angle then upAux coincides with the up, otherwise has the opposite direction of the up vector • glRotatef(acos(angleCosine)*180/3.14,upAux[0], upAux[1], upAux[2]);

(21)

Camera Position alignment

•  No popping

•  Steady billboards with camera rotation

•  Billboards rotate with linear movements of camera

(22)
(23)
(24)
(25)
(26)
(27)

Element of the

Flare Length Scale Image Scale

Primary Flare length 1.0 First Halo length/2 .5 Small Burst length/3 .25 Next Halo length/8 1.0 Next Burst -(length/2) .5 Next Halo -(length/4) .25 Next Burst -(length/5.5) .25

(28)
(29)
(30)

Skybox

•  Desenhar céu através de um cubo com as faces viradas para o interior

•  Texturar cada uma das 6 faces com uma vista do céu

•  Textura apenas correcta para o ponto de vista a partir do qual ela foi gerada

•  Manter a skybox centrada na câmara

•  O céu está muito (infinitamente) distante •  A câmara nunca chega perto do céu

•  As texturas do céu parecem ser sempre correctas

•  Desenhar a skybox antes de tudo o resto

•  Usar o nevoeiro para ocultar o tamanho limitado do terreno e tornar mais natural a transição para o céu

•  OpenGL 1.3 tem um modo especial de mapeamento cúbico

de textura, o que permite mapear a sky box com uma única textura

(31)
(32)

Sistemas de Partículas

•  William T. Reeves, Particle Systems - A Technique for Modeling a Class of Fuzzy Objects”, Computer Graphics (Proc. SIGGRAPH’83), Vol. 17, No3 pp. 359-376, 1983

•  Usado num projecto de efeitos especiais para o filme “Star Trek II: The Wrath of Khan”

•  O sistema permite a representação de objectos, cujas superfícies não são bem definidas, através de uma colecção de partículas, utilizando as leis de mecânica de Newton

•  Extremamente úteis para simulação de fenómenos físicos e naturais. Modo de representar entidades como: água, fogo, fumo, explosões, conjuntos de animais (bandos, manadas, cardumes), elementos da natureza em geral (neve, chuva, relva, furacões..)

•  Actualmente quase todos os jogos os usam

•  É necessário desenhar um sistema eficiente e flexível.

•  Um sistema mal desenhado pode ter um impacto

(33)

Sistemas de Partículas (SP)

•  Representação de um objecto como uma nuvem de

partículas a qual define o seu volume (ao invés de se

utilizar a primitiva poligono utiliza-se a primitiva partícula)

•  As partículas não são entidades estáticas, ou seja, o SP evolui ao longo do tempo: as partículas do sistema:

•  nascem; •  movem-se;

•  alteram a sua aparência; •  morrem

•  Um objecto representado por um SP é não-determinístico; a sua forma nunca é completamente definida

•  SPs são um exemplo de modelação procedimental

(34)

Propriedades dum SP

•  Partículas são simples (computacionalmente eficientes)

•  A geração e os atributos das partículas são

procedimentais, podem ser, por ex., resultados de cálculos da ciência e da engenharia

•  LOD é fácil - variar o número de partículas consoante a distância à câmara

•  Opção boa na representação de objectos

complexos, de objectos amorfos bem como na modelação de comportamentos complexos

(35)

Modelo básico dum SP

O que é um SP?

•  Colecção de partículas

•  Conjunto de funções que controla o comportamento

(alteração dos atributos) das partículas ao longo do tempo

•  Em cada frame:

1.  Geração de partículas com atributos iniciais (frequente

o uso de métodos estocásticos)

2.  Destruição das partículas cujo tempo de vida se

esgotou

3.  Alteração dos atributos das partículas: posição, cor,

etc.

(36)

A estrutura de dados

•  Desenhar uma estrutura de dados eficiente é essencial.

•  Deve fornecer, não só desempenho, como também flexibilidade.

•  Deve permitir vários tipos de sistemas, bem como várias maneiras de comportamento das partículas.

•  Deve permitir um fácil integração com ferramentas já existentes.

(37)
(38)

Atributos de uma partícula

•  Posição (x, y e z)

•  Vector Velocidade (vx, vy e vz)

•  Aceleração (ax, ay e az)

•  Tamanho

•  Cor e Transparência

•  Forma

•  Tempo de Vida

(39)

Método Euler – Posição e Velocidade

a(t) ≈ (v(t+h) - v(t))/h e v(t) ≈ (y(t+h) - y(t))/h, onde h = ∆t Assim:

  y(t+h) ≈ y(t) + h v(t)

(40)
(41)
(42)
(43)

Gestor de sistemas

•  Gere todos os sistemas!

•  Normalmente efectua funções de regulação a cada um dos sistemas, mas também pode

(44)

Considerações sobre SPs

•  Sistemas de partículas lidam com enormes quantidades de dados

•  É necessária uma gestão de memória eficaz!

•  Exemplo:

•  Imaginem um missil disparado que vai deixando

um rasto de fumo.

•  Quanto maior a distância percorrida pelo missil

maior a quantidade de fumo gerada.

•  As partículas vão aumentando até chegar a um

limite impraticável – uso adequado do tempo de vida

•  Mas o primeiro fumo vai desaparecendo!

•  E agora? Quando o fumo desaparecer o que se faz

(45)

Considerações sobre SPs

•  Podemos destruir a partícula, quando ela deixa de estar visível!

•  ATENÇÃO! Devemos evitar destruir a partícula.

•  A alocação e libertação de memória são muito pesadas em termos de desempenho!

•  Lidar com partículas inactivas é algo com que se tem que lidar sempre.

•  Deve ser algo muito simples!

•  A solução é re-aproveitar as partículas, não as destruindo.

(46)

Considerações sobre SPs

•  As partículas reaproveitam-se utilizando uma técnica que se chama de respawn!

•  Consiste em inicializar a partícula que “morre”, colocando-a de novo no emissor.

•  Exemplos:

•  http://www.jhlabs.com/java/particles2.html

(47)

Particle characteristics

•  Each new particle has as attributes:

•  Initial position (x, y and z); •  Initial speed (x, y and z); •  Size;

•  Color;

•  Initial transparency; •  Shape;

•  Life time;

•  Speed that the live goes away (by frame); •  Acceleration (x, y and z).

(48)

Particle characteristics

•  The position of each particle on each frame could be found by knowing its velocity.

•  This can be modified by the acceleration.

•  The color, the opacity and size of the particle can be modified by parameters.

•  These parameters can be the same to all the particles or stochastic for each particle.

(49)

Particle characteristics

•  When each particle is created a life time is associated to it.

•  After each frame, the life time is reduced by the speed that the live goes away (by frame), when the life time is zero the particle is destroyed.

•  When a particle is outside an interest region (the screen of the computer, for example) it could be destroyed.

(50)
(51)
(52)
(53)
(54)

Reflections and Shadows on

Planar Surfaces

(55)

Reflections - Motivation

•  Not easy to use ray-tracing techniques to simulate real-time reflections

•  By using “tricks” and functionalities provided by the graphic hardware such effects can be

(56)

Planar reflections

•  Mirror: Ideal reflector planar surface

•  Color calculated by following the reflected ray

•  Alternative: to use reflected geometry through the mirror plane

•  The reflected image of the object is simply the object itself, physically reflected through the mirror plane.

(57)

Planar reflections

•  Assume plane is y=0

•  Then apply a mirror scaling matrix: glScalef

(1,-1,1);

•  Effect:

(58)
(59)

Planar reflections

How should you render?

1) the ground plan polygon into the

stencil buffer

2) the scaled (1,-1,1) model, but mask

with stencil buffer

3) the ground plane (semi-transparent)

4) the unscaled model

(60)

Another example

•  Instead of the scale-trick, you can reflect the

camera position and direction in the plane

•  Then render reflection image from there

Im age c ourt es y of K as pe r H oe y N ie ls en

(61)

Planar Reflections

Operations

•  plane y=0: use scale S(1,-1,1) to reflect the geometry and light sources

•  Arbitrary reflector plane: translate to origin and rotate in order to align with y=0, scale; then invert the two initial transforms

(62)

Reflections OpenGL considerations

•  The reflector has to be partially transparent

•  Setting properly backface culling since mirror scale matrix flips the polygon orientation

•  Avoid that reflected geometry can appear at places where there is no reflector geometry. How?

•  Objects that are on the far side (behind) the mirror should not be reflected. How? To set a user-defined clipping plane with the reflector plane equation properly oriented.

(63)

Reflexões em Superfícies Planas:

Exercício

•  O exercício consiste em implementar um pequeno

programa que permita a navegação dentro de uma cena

composta por um conjunto de objectos e um chão capaz de reflectir esses mesmos objectos. Ao observarmos o espaço debaixo do chão, não deve de ser possível ver nenhum

objecto.

•  Propõem-se as seguintes fases para a realização do algoritmo:

•  Fase 1: Desenhar os objectos reflectidos; limitar o

desenho dos objectos reflectidos à superfície de reflexão usando o stencil buffer.

•  Fase 2: Desenhar a superfície de reflexão (o chão neste

caso)

(64)

Planar Shadows

•  Provides important visual cues about object placement in the world:

- Distances and depth relationships between objects are used by our brain to generate the perception of 3D space

•  Occluders cast shadows onto receivers

(65)

Real-Time Planar Shadows

•  Pipeline de visualização tradicional apenas entra em conta com efeitos de reflexão local e não considera oclusões entre uma fonte de luz e objectos que

estejam a ser iluminados.

•  Algoritmos como ray-tracing ou radiosidade

apresentam soluções elegantes para o cálculo de sombras, mas não podem ser executados em tempo real

•  Técnicas para calcular sombras em tempo real , baseadas no pipeline de visualização tradicional, recorrendo ao hardware actual:

•  Sombras Planares

•  Shadow Volumes

(66)

Blinn Technique (1988)

•  Jim Blinn, "Me and My (Fake) Shadow", IEEE

Computer Graphics and Applications, January 1988, algorithm where arbitrary objects cast shadows of onto planar surfaces

•  Esta técnica apenas calcula sombras sobre uma única superfície planar previamente escolhida, provenientes de objectos (quaisquer) que se encontrem entre a fonte de luz e a superfície

•  Não considera sombras que os objectos possam projectar uns sobre os outros.

(67)

Blinn Technique (cont.)

•  Goal: for a point light source, derive the matrix that projects the vertices of an arbitrary object (occluder) on to a ground plane (receiver). Light source is

located at ‘l’, the vertex to be projected is at ‘v’ and the projected vertex is at ‘p’.

(68)

Linear Equation (cont.)

•  2 equations system: parametric line and plane equation

(69)

Planar Shadow Projection Matrix

•  The linear equation can be converted into a projection matrix M:

•  M should be concatenated with the ModelView matrix

(70)

Some OpenGL considerations

•  Take measures to avoid allowing the projected objects to be

rendered beneath the ground. Why?

•  Safer method: draw the ground plane first, then draw the projected

polygons with the z-buffer off, then render the original geometry. Why?

•  Instead of render the shadows with dark color, we could “dark” the

existing color in the color buffer by using blending. How?

•  Use of stencil buffer:

1) to avoid that projected shadows can fall outside of our ground plane 2) to ensure that each pixel is covered at most once (when, why and how?)

•  By darking the existing color, shadows can exhibit specular color.

WRONG: projected objets should have no illumination

•  Possible solution: use the stencil buffer to mark all the shadow

points on the ground plane, then re-draw the ground with light

source turned off: only the ground fragments corresponding to the marked points in the stencill will be shown.

Referências

Documentos relacionados

Both the distribution of toxin concentrations and toxin quota were defined by epilimnetic temperature (T_Epi), surface temperature (T_Surf), buoyancy frequency (BuoyFreq) and

Promovido pelo Sindifisco Nacio- nal em parceria com o Mosap (Mo- vimento Nacional de Aposentados e Pensionistas), o Encontro ocorreu no dia 20 de março, data em que também

nesta nossa modesta obra O sonho e os sonhos analisa- mos o sono e sua importância para o corpo e sobretudo para a alma que, nas horas de repouso da matéria, liberta-se parcialmente

Ordenação de constituintes em interrogativas de conteúdo na história do PB Ao longo da história do PB, três fenômenos inovadores atingem a estrutura das Interrogativas de

3.3 o Município tem caminhão da coleta seletiva, sendo orientado a providenciar a contratação direta da associação para o recolhimento dos resíduos recicláveis,

Apesar dos esforços para reduzir os níveis de emissão de poluentes ao longo das últimas décadas na região da cidade de Cubatão, as concentrações dos poluentes

Para analisar as Componentes de Gestão foram utilizadas questões referentes à forma como o visitante considera as condições da ilha no momento da realização do

Neste estudo foram estipulados os seguintes objec- tivos: (a) identifi car as dimensões do desenvolvimento vocacional (convicção vocacional, cooperação vocacio- nal,