Академический Документы
Профессиональный Документы
Культура Документы
Aula 9
2
A história até aqui...
Desenho de objetos 2D
SpriteBatch SB, Texture2D tex
SB.Draw(Tex,…
Uso de Fontes
SpriteBatch SB, SpriteFont Fon
SB.DrawString (Fon,...
Matrix.CreateRotationX,
Matrix.CreateRotationY e
Matrix.CreateRotationZ – cria matrizes de
transformação para cada eixo
View Matrices:
Matriz que calcula uma posição e orientação de
câmera
Matrix.CreateLookAt
Projection Matrices:
Matrizes que calculam projeção de perspectiva
Matrix.CreatePerspectiveFieldOfView
Matrix.CreatePerspectiveOffCenter
Matrix.CreatePerspective
effect.Begin();
foreach(EffectPass CurrentPass in
effect.CurrentTechnique.Passes)
{
CurrentPass.Begin();
// Código que realiza o desenho 3D
CurrentPass.End();
}
effect.End();
6
Revisão - Desenhando modelos
Carregar o modelo
tankModel = content.Load<Model>(@"Content\Cube");
Desenhar o modelo
foreach (ModelMesh mesh in tankModel.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = world;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
}
mesh.Draw();
}
7
Revisão: Usando câmeras
É muito simples!
Criar ou inserir um componente de câmera no
projeto
Usar as propriedades de view e projection!
// Draw the model
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = world;
effect.View = myCamera.View;
effect.Projection = myCamera.Projection;
effect.EnableDefaultLighting();
}
// Draw each mesh of the model
mesh.Draw();
}
8
Shaders: Visão Geral
Para que servem Shaders?
Transformar coordenadas desde modelo até tela:
9
Shaders: Visão Geral
Para que servem Shaders?
Definir cores para vértices
Mapear texturas nos modelos
Definir como as fontes de luz impactarão no
modelo
Criar efeitos diversos, baseados em
transformações dos vértices, pixels ou geometria:
Fog
Blur
Efeitos em toda tela, como “terremotos”
Alteração dinâmica do modelo
Muitos etc
10
Shaders: Visão Geral
Palavra do Especialista
Palestra de Bruno Evangelista, apresentada na
GameFest SP
Disponível em http://www.BrunoEvangelista.com
11
Um pouco sobre iluminação
Phong
Fórmula simples, de cálculo rápido
12
Um pouco sobre iluminação
Luz ambiente
Ilumina por igual todos os pontos de um objeto
É uma constante
Ex:
Ref: http://www.BrunoEvangelista.com
13
Um pouco sobre iluminação
Luz Difusa
Ref: http://www.BrunoEvangelista.com
14
Um pouco sobre iluminação
Luz especular
Ref: http://www.BrunoEvangelista.com
15
Um pouco sobre iluminação
Phong
Luz ambiente + Luz difusa + Luz especular
=
16
Estrutura de um Shader
shared float4x4 world; Parâmetros do shader
shared float4x4 view; • “Shared” indica
parâmetro usado por
shared float4x4 projection;
mais de um shader
float4 baseColor;
struct VertexShaderOutput
{
float4 Position : POSITION;
float4 Color : COLOR; Estruturas usadas no
}; shader
• “POSITION”,
“COLOR”, etc são
17
Estrutura de um Shader
Funções do shader
VertexShaderOutput SimpleShader( • Podem ser criadas à
float3 position : POSITION, vontade
float3 color : COLOR ) • As “principais” são
{ associadas aos passos do
VertexShaderOutput output; shader no bloco de
//generate the world-view-proj matrix “técnica” (próximo slide)
float4x4 wvp = mul(mul(world, view), projection);
//transform the input position to the output
output.Position = mul(float4(position, 1.0), wvp);
output.Color = color;
//return the output structure
Funções do shader
return output;
• Esta função retorna uma estrutura
}
do tipo VertexShaderOutput
(definida no slide anterior)
float4 SimplePixelShader(PixelShaderInput input) : COLOR
{
//return a mix of the model and base colors
return smoothstep(clamp(input, 0, 0.9), normalize(baseColor), 0.5);
}
18
Estrutura de um Shader Técnicas e Passos
• Nosso programa precisa
technique VertexLighting
escolher as técnicas e passos
{ a serem usadas, ou realizar
pass P0 loop por todas
{
//set the VertexShader state to the vertex shader function
VertexShader = compile vs_2_0 DiffuseLighting();
Estados do shader
• É aqui que associamos as
funções a cada estado do
shader (VertexShader,
PixelShader, etc)
19
Criando um shader simples
Algumas das funções de linguagem HLSL:
dot - Calcula o produto escalar entre dois vetores.
mul - Realiza multiplicação entre vetores e matrizes.
normalize - Normaliza um vetor.
reflect - Reflete um vetor incidente a uma normal.
refract – calcula o vetor de refração em relação à normal
saturate - Satura os valores entre 0.0 e 1.0
distance – retorna a distância entre dois pontos
cross – retorna o produto vetorial (cross product) de dois
vetores 3D
21
Criando um shader simples
Semânticas (Semantics): Vertex Shader
Input Description Type
BINORMAL[n] Binormal float4
BLENDINDICES[n] Blend indices uint
BLENDWEIGHT[n] Blend weights float
COLOR[n] Diffuse and specular color float4
NORMAL[n] Normal vector float4
POSITION[n] Vertex position in object space. float4
POSITIONT Transformed vertex position. float4
PSIZE[n] Point size float
TANGENT[n] Tangent float4
TEXCOORD[n] Texture coordinates float4
Output Description Type
COLOR[n] Diffuse or specular color float4
FOG Vertex fog float
Position of a vertex in homogenous space. Compute position
in screen-space by dividing (x,y,z) by w. Every vertex shader
POSITION[n] must write out a parameter with this semantic. float4
PSIZE Point size float
TESSFACTOR[n] Tessellation factor float
TEXCOORD[n] Texture coordinates float4
22
Criando um shader simples
Semânticas (Semantics): Pixel Shader
23
Criando um shader simples
Usando o Shader em seu programa
1. Carregar o efeito
effect = content.Load<Effect>(@"Content\" + effectName);
2. Carregar os parâmetros
view = effect.Parameters["view"];
projection = effect.Parameters["projection"];
world = effect.Parameters["world"];
ambientLightColor = effect.Parameters["ambientColor"];
24
Criando um shader simples
Usando o Shader em seu programa
3. Setar os parâmetros
ambientLightColor.SetValue(value);
26
Exemplo 2: Iluminação por vértices
27
Para saber mais
Todos os links para tudo o que você precisa
saber sobre shaders (tutoriais, exemplos,
indicação de livros, etc):
http://forums.xna.com/thread/24109.aspx
Referência da HLSL
http://msdn2.microsoft.com/en-
us/library/bb509638.aspx
28
Perguntas?
29