SlideShare une entreprise Scribd logo
1  sur  46
Beginning Direct3D Game Programming:
9. Shader Programming
jintaeks@gmail.com
Division of Digital Contents, DongSeo University.
May 2016
Shaders
 Vertex shaders are executable programs that process vertex
data.
 In the fixed function pipeline, Vertex processing takes
primitive vertex data from model space and converts it into
vertex data in projection space.
2
Vertex Processing
 Vertex processing converts data from model space to
projection space.
3
Vertex Blending
 Blending combines one or more sets of vertex data to
animate vertex data.
 Vertex blending uses one set of vertex data and one or more
transforms (each with a corresponding weight).
4
Primitive Processing
 After vertex processing, primitive processing and pixel
processing convert per-vertex data into the final pixels that
will be rendered.
5
■ Clipping. Clipping or removing geometry that’s outside of the
viewing frustum to maximize rendering efficiency.
■ Homogeneous divide. Converting the x,y,z vertex data to
nonhomogeneous space before sending the data to the
rasterizer.
■ Viewport scaling. Scaling 2-D projection space to 2-D screen
space.
■ Triangle set up. Preparing triangle-attribute interpolators and
converting per-vertex attributes into per-pixel attributes.
6
Pixel Processing
 The output of primitive processing is vertex data interpolated
per pixel.
 Pixel processing blends several per-pixel data types and
texture samples (if any) into output pixel colors.
7
Part 1
■ Sample texture. Sample one or more textures.
■ Blend. Blend per-pixel attributes, typically diffuse and
specular color and/or texture samples.
8
Part 2
■ Alpha test. Apply an alpha test to see if the pixel color will
affect the final pixel color.
■ Depth test. Update the depth buffer with the pixel depth if
the pixel is visible.
■ Stencil test. Apply a stencil test to see if the pixel will affect
the final pixel color.
■ Per-pixel fog. Apply a fog color to the pixel color.
■ Alpha blend. Apply pixel alpha to create a transparent or
semitransparent blend between a source pixel and a frame
buffer pixel.
■ Dither. Use a dithering algorithm to blend adjacent pixels for
a more consistent color range.
■ Gamma. Apply a gamma correction to the final frame buffer
pixel color.
9
Part 1(detailed)
10
■ Texture data. Texture resources such as a texture file or a
render target.
■ Sampler. Used to sample textures, which means to use the
texture coordinates to look up a texture color.
– Texture filtering influences the quality of the information (typically
color) that is sampled from a texture.
11
Programmable Shader
 Assembly Shader in DirectX 8.
12
HLSL: High-Level Shading Language
 HLSL is a shading language developed by Microsoft for
the Direct3D 9 API to augment the shader assembly language.
 HLSL is analogous to the GLSL shading language used with
the OpenGL standard. It is very similar to the
Nvidia Cg shading language.
 HLSL programs come in five forms:
– pixel shaders (fragment in GLSL)
– vertex shaders
– geometry shaders
– compute shaders
– tessellation shaders (Hull and Domain shaders).
13
Vertex Shader Comparison
 VS 2.0 = DirectX 9.0 original Shader Model 2 specification.
 VS 2.0a = NVIDIA GeForce FX/PCX-optimized model, DirectX
9.0a.
 VS 3.0 = Shader Model 3.0, DirectX 9.0c.
 VS 4.0 = Shader Model 4.0, DirectX 10.
 VS 4.1 = Shader Model 4.1, DirectX 10.1.
 VS 5.0 = Shader Model 5.0, DirectX 11.
14
15
Vertex Shader Example
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
float3 vNormal : NORMAL,
float2 vTexCoord0 : TEXCOORD0 )
{
VS_OUTPUT Output;
float3 vNormalWorldSpace;
float4 vAnimatedPos = vPos;
// Transform the position from object space to homogeneous projection space
Output.Position = mul(vAnimatedPos, g_mWorldViewProjection);
// Transform the normal from object space to world space
vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld));
// Compute simple directional lighting equation
float3 vTotalLightDiffuse = float3(0,0,0);
vTotalLightDiffuse += g_LightDiffuse * max( 0, dot( vNormalWorldSpace, g_LightDir ) );
16
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
float3 vNormal : NORMAL,
float2 vTexCoord0 : TEXCOORD0 )
{
…
// Compute simple directional lighting equation
float3 vTotalLightDiffuse = float3(0,0,0);
vTotalLightDiffuse += g_LightDiffuse * max( 0, dot( vNormalWorldSpace, g_LightDir ) );
Output.Diffuse.rgb = g_MaterialDiffuseColor * vTotalLightDiffuse +
g_MaterialAmbientColor * g_LightAmbient;
Output.Diffuse.a = 1.0f;
// Just copy the texture coordinate through
Output.TextureUV = vTexCoord0;
return Output;
}
17
Pixel Shader Comparison
 PS 2.0 = DirectX 9.0 original Shader Model 2 specification.
 PS 2.0a = NVIDIA GeForce FX/PCX-optimized model, DirectX
9.0a.
 PS 2.0b = ATI Radeon X700, X800, X850, FireGL X3-256,
V5000, V5100 and V7100 shader model, DirectX 9.0b.
 PS 3.0 = Shader Model 3.0, DirectX 9.0c.
 PS 4.0 = Shader Model 4.0, DirectX 10.
 PS 4.1 = Shader Model 4.1, DirectX 10.1.
 PS 5.0 = Shader Model 5.0, DirectX 11.
18
19
Pixel Shader Example
struct VS_OUTPUT
{
float4 Position : POSITION; // vertex position
float4 Diffuse : COLOR0;
// vertex diffuse color (note that COLOR0 is clamped from 0..1)
float2 TextureUV : TEXCOORD0; // vertex texture coords
};
PS_OUTPUT RenderScenePS( VS_OUTPUT In )
{
PS_OUTPUT Output;
// Lookup mesh texture and modulate it with diffuse
Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse;
return Output;
}
20
Effects(Direct3D 9)
 A Microsoft DirectX effect enables the integration of vertex
and pixel shaders with pipeline state to render objects.
 Effects also provide a convenient way to write shaders for
different hardware versions.
 An effect can replace the vertex processing and part of the
pixel processing performed by the graphics pipeline.
21
Effects and the 3D Pipeline
 Vertex and pixel processing can be performed by the fixed
function pipeline, or can be implemented with programmable
shaders.
 The input data tessellation, primitive processing, and data
outputs are controlled by pipeline state. All this can be
integrated into an effect.
22
Effects can save and restore states
 Shader state.
– This includes creating and deleting shaders, setting shader constants,
setting shader state, and rendering with shaders.
 Texture and sampler state.
– This includes specifying texture files, initializing texture stages,
creating sampler objects, and setting sampler state.
 Other pipeline state.
– This includes states for setting transformations, lighting, materials, and
rendering options.
 All rendering in an effect is done within a matching pair of
ID3DXEffect::Begin and ID3DXEffect::End calls.
23
Effect State
 Effect state initializes the pipeline for processing pipeline data.
Effect variables hold effect state values.
technique TVertexShaderOnly_Asm
{
pass P0
{
// lighting
Lighting = FALSE;
SpecularEnable = TRUE;
// samplers
Sampler[0] = (Sampler);
// texture stages
ColorOp[0] = MODULATE;
ColorArg1[0] = TEXTURE;
ColorArg2[0] = DIFFUSE;
AlphaOp[0] = MODULATE;
24
Writing an Effect
 Writing an effect requires that you
understand effect syntax, and generate the
required state information.
 An effect is typically encapsulated into an
effect file (.fx) but could also be written as a
text string in an application.
25
Simple Effect Example
// texture
texture Tex0 < string name = "tiger.bmp"; >;
sampler Sampler = sampler_state
{
Texture = (Tex0);
MipFilter = LINEAR;
MinFilter = LINEAR;
MagFilter = LINEAR;
};
float4x4 matWorldViewProj : WORLDVIEWPROJ;
struct VS_OUTPUT
{
float4 Pos : POSITION;
float2 Tex : TEXCOORD0;
};
26
VS_OUTPUT VS( float3 Pos : POSITION, float2 Tex : TEXCOORD0)
{
VS_OUTPUT Out = (VS_OUTPUT)0;
Out.Pos = mul(Pos, matWorldViewProj);
Out.Tex = Tex;
return Out;
}
technique TVertexShaderOnly_HLSL
{
pass P0
{
// lighting
Lighting = FALSE;
SpecularEnable = TRUE;
// samplers
Sampler[0] = (Sampler);
// texture stages
ColorOp[0] = MODULATE;
27
// texture stages
ColorOp[0] = MODULATE;
ColorArg1[0] = TEXTURE;
ColorArg2[0] = DIFFUSE;
AlphaOp[0] = MODULATE;
AlphaArg1[0] = TEXTURE;
AlphaArg2[0] = DIFFUSE;
ColorOp[1] = DISABLE;
AlphaOp[1] = DISABLE;
// shaders
VertexShader = compile vs_1_1 VS();
PixelShader = NULL;
}
}
28
Effect Example: BasicHLSL sample in DirectX Sdk
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
float4 g_MaterialAmbientColor; // Material's ambient color
float4 g_MaterialDiffuseColor; // Material's diffuse color
float3 g_LightDir; // Light's direction in world space
float4 g_LightDiffuse; // Light's diffuse color
float4 g_LightAmbient; // Light's ambient color
texture g_MeshTexture; // Color texture for mesh
float g_fTime; // App's time in seconds
float4x4 g_mWorld; // World matrix for object
float4x4 g_mWorldViewProjection; // World * View * Projection matrix
29
Texture samplers, Vertex shader output structure
//--------------------------------------------------------------------------------------
// Texture samplers
//--------------------------------------------------------------------------------------
sampler MeshTextureSampler =
sampler_state
{
Texture = <g_MeshTexture>;
MipFilter = LINEAR;
MinFilter = LINEAR;
MagFilter = LINEAR;
};
//--------------------------------------------------------------------------------------
// Vertex shader output structure
//--------------------------------------------------------------------------------------
struct VS_OUTPUT
{
float4 Position : POSITION; // vertex position
float4 Diffuse : COLOR0; // vertex diffuse color (note that COLOR0 is clamped from 0..1)
float2 TextureUV : TEXCOORD0; // vertex texture coords
};
30
Vertex shader
//--------------------------------------------------------------------------------------
// This shader computes standard transform and lighting
//--------------------------------------------------------------------------------------
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
float3 vNormal : NORMAL,
float2 vTexCoord0 : TEXCOORD0,
uniform int nUnused,
uniform bool bTexture,
uniform bool bAnimate )
{
VS_OUTPUT Output;
float3 vNormalWorldSpace;
float4 vAnimatedPos = vPos;
// Transform the position from object space to homogeneous projection space
Output.Position = mul(vAnimatedPos, g_mWorldViewProjection);
// Transform the normal from object space to world space
vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space)
31
// Transform the normal from object space to world space
vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space)
// Compute simple directional lighting equation
float3 vTotalLightDiffuse = float3(0,0,0);
vTotalLightDiffuse += g_LightDiffuse * max( 0, dot( vNormalWorldSpace, g_LightDir ) );
Output.Diffuse.rgb = g_MaterialDiffuseColor * vTotalLightDiffuse +
g_MaterialAmbientColor * g_LightAmbient;
Output.Diffuse.a = 1.0f;
// Just copy the texture coordinate through
if( bTexture )
Output.TextureUV = vTexCoord0;
else
Output.TextureUV = 0;
return Output;
}
32
Pixel shader
// Pixel shader output structure
struct PS_OUTPUT
{
float4 RGBColor : COLOR0; // Pixel color
};
// This shader outputs the pixel's color by modulating the texture's
// color with diffuse material color
//--------------------------------------------------------------------------------------
PS_OUTPUT RenderScenePS( VS_OUTPUT In, uniform bool bTexture )
{
PS_OUTPUT Output;
// Lookup mesh texture and modulate it with diffuse
if( bTexture )
Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse;
else
Output.RGBColor = In.Diffuse;
return Output;
}
33
technique
//--------------------------------------------------------------------------------------
// Renders scene to render target
//--------------------------------------------------------------------------------------
technique RenderSceneWithTexture1Light
{
pass P0
{
VertexShader = compile vs_2_0 RenderSceneVS( 1, false, false );
PixelShader = compile ps_2_0 RenderScenePS( false ); // trivial pixel shader (could use FF instead
if desired)
}
}
technique RenderSceneWithTexture2Light
{
pass P0
{
VertexShader = compile vs_2_0 RenderSceneVS( 2, true, true );
PixelShader = compile ps_2_0 RenderScenePS( true ); // trivial pixel shader (could use FF instead
if desired)
}
}34
Effects Contain One or More Techniques and Passes
technique T0
{
pass P0
{ ... }
}
technique T1
{
pass P0
{ ... }
pass P1
{ ... }
}
35
Using an Effect: Creating an Effect
ID3DXEffect* g_pEffect = NULL;
DWORD dwShaderFlags = 0;
dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
dwShaderFlags |= D3DXSHADER_NO_PRESHADER;
// Read the D3DX effect file
WCHAR str[MAX_PATH];
DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL.fx" );
D3DXCreateEffectFromFile(
pd3dDevice,
str,
NULL, // CONST D3DXMACRO* pDefines,
NULL, // LPD3DXINCLUDE pInclude,
dwShaderFlags,
NULL, // LPD3DXEFFECTPOOL pPool,
&g_pEffect,
NULL );
36
Render an Effect
// Apply the technique contained in the effect
g_pEffect->Begin(&cPasses, 0);
for (iPass = 0; iPass < cPasses; iPass++)
{
g_pEffect->BeginPass(iPass);
// Only call CommitChanges if any state changes have happened
// after BeginPass is called
g_pEffect->CommitChanges();
// Render the mesh with the applied technique
g_pMesh->DrawSubset(0);
g_pEffect->EndPass();
}
g_pEffect->End();
37
Use Semantics to Find Effect Parameters
 In effect file, the semantic is located following a colon (:) after
the parameter name. For instance:
float4x4 matWorldViewProj : WORLDVIEWPROJ;
 The effect interface can use a semantic to get a handle to a
particular effect parameter. For instance:
D3DHANDLE handle = m_pEffect->GetParameterBySemantic(NULL,
"WORLDVIEWPROJ");
38
Add Parameter Information with Annotations
 Annotations are user-specific data that can be attached to
any technique, pass, or parameter.
– An annotation is a flexible way to add information to individual
parameters.
 Annotation declarations are delimited by angle brackets. An
annotation contains:
– A data type.
– A variable name.
– An equals sign (=).
– The data value.
– A ending semicolon (;).
texture Tex0 < string name = "tiger.bmp"; >;
39
texture Tex0 < string name = "tiger.bmp"; >;
 The annotation is attached to the texture object and specifies
the texture file that should be used to initialize the texture
object.
 The annotation does not initialize the texture object, it is
simply a piece of user information.
 An application can read the annotation with
ID3DXBaseEffect::GetAnnotation.
40
Set Effect Parameters
m_pEffect->SetTechnique( "RenderScene" );
m_pEffect->BeginParameterBlock();
D3DXVECTOR4 v4( Diffuse.r, Diffuse.g, Diffuse.b, Diffuse.a );
m_pEffect->SetVector( "g_vDiffuse", &v4 );
m_pEffect->SetFloat( "g_fReflectivity", fReflectivity );
m_pEffect->SetFloat( "g_fAnimSpeed", fAnimSpeed );
m_pEffect->SetFloat( "g_fSizeMul", fSize );
m_hParameters = m_pEffect->EndParameterBlock();
41
Practice: Build BasicHLSL sample project in Sdk
 Examine all statements related to 'g_pEffect'.
ID3DXEffect* g_pEffect = NULL; // D3DX effect interface
 Examine all statements in the effect file related to 'g_pEffect'.
42
Fix HLSL error
43
 Replace 'tiny.x' mesh with 'teapot.x'
 Disable the vertex animation in effect file.
 Modify diffuse color of lights and check the result.
44
References
 Kris Gray, "DirectX 9 Programmable Graphics Pipeline",
Microsoft Press.
45
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks

Contenu connexe

Tendances

Tendances (20)

Beyond porting
Beyond portingBeyond porting
Beyond porting
 
CS 354 Understanding Color
CS 354 Understanding ColorCS 354 Understanding Color
CS 354 Understanding Color
 
OpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
OpenGL NVIDIA Command-List: Approaching Zero Driver OverheadOpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
OpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
 
CS 354 Blending, Compositing, Anti-aliasing
CS 354 Blending, Compositing, Anti-aliasingCS 354 Blending, Compositing, Anti-aliasing
CS 354 Blending, Compositing, Anti-aliasing
 
CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and Culling
 
Project Fortress
Project FortressProject Fortress
Project Fortress
 
CS 354 Graphics Math
CS 354 Graphics MathCS 354 Graphics Math
CS 354 Graphics Math
 
FlameWorks GTC 2014
FlameWorks GTC 2014FlameWorks GTC 2014
FlameWorks GTC 2014
 
CS 354 Pixel Updating
CS 354 Pixel UpdatingCS 354 Pixel Updating
CS 354 Pixel Updating
 
Advancements in-tiled-rendering
Advancements in-tiled-renderingAdvancements in-tiled-rendering
Advancements in-tiled-rendering
 
Trident International Graphics Workshop 2014 5/5
Trident International Graphics Workshop 2014 5/5Trident International Graphics Workshop 2014 5/5
Trident International Graphics Workshop 2014 5/5
 
Rethinking Attention with Performers
Rethinking Attention with PerformersRethinking Attention with Performers
Rethinking Attention with Performers
 
CS 354 More Graphics Pipeline
CS 354 More Graphics PipelineCS 354 More Graphics Pipeline
CS 354 More Graphics Pipeline
 
Modern OpenGL Usage: Using Vertex Buffer Objects Well
Modern OpenGL Usage: Using Vertex Buffer Objects Well Modern OpenGL Usage: Using Vertex Buffer Objects Well
Modern OpenGL Usage: Using Vertex Buffer Objects Well
 
Foreground detection using gaussian mixture models matlab
Foreground detection using gaussian mixture models   matlabForeground detection using gaussian mixture models   matlab
Foreground detection using gaussian mixture models matlab
 
GLSL
GLSLGLSL
GLSL
 
CS 354 Viewing Stuff
CS 354 Viewing StuffCS 354 Viewing Stuff
CS 354 Viewing Stuff
 
Dx11 performancereloaded
Dx11 performancereloadedDx11 performancereloaded
Dx11 performancereloaded
 
ARCHITECTURAL CONDITIONING FOR DISENTANGLEMENT OF OBJECT IDENTITY AND POSTURE...
ARCHITECTURAL CONDITIONING FOR DISENTANGLEMENT OF OBJECT IDENTITY AND POSTURE...ARCHITECTURAL CONDITIONING FOR DISENTANGLEMENT OF OBJECT IDENTITY AND POSTURE...
ARCHITECTURAL CONDITIONING FOR DISENTANGLEMENT OF OBJECT IDENTITY AND POSTURE...
 
CS 354 Acceleration Structures
CS 354 Acceleration StructuresCS 354 Acceleration Structures
CS 354 Acceleration Structures
 

En vedette

Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeksBeginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
JinTaek Seo
 

En vedette (20)

Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeksBeginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
 
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeksBeginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
 
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeksBeginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
 
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeksBeginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
 
Beginning direct3d gameprogramming01_20161102_jintaeks
Beginning direct3d gameprogramming01_20161102_jintaeksBeginning direct3d gameprogramming01_20161102_jintaeks
Beginning direct3d gameprogramming01_20161102_jintaeks
 
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksBeginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
 
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
 
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeksBeginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
 
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeksBeginning direct3d gameprogramming05_thebasics_20160421_jintaeks
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
 
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeksBeginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
 
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeksBeginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
 
Beginning direct3d gameprogramming07_lightsandmaterials_20161117_jintaeks
Beginning direct3d gameprogramming07_lightsandmaterials_20161117_jintaeksBeginning direct3d gameprogramming07_lightsandmaterials_20161117_jintaeks
Beginning direct3d gameprogramming07_lightsandmaterials_20161117_jintaeks
 
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeksBeginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
 
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeksBeginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
 
Shaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the BestShaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the Best
 
Writing shaders - YOU can do it!
Writing shaders - YOU can do it!Writing shaders - YOU can do it!
Writing shaders - YOU can do it!
 
Shader Programming With Unity
Shader Programming With UnityShader Programming With Unity
Shader Programming With Unity
 
Unity Surface Shader for Artist 01
Unity Surface Shader for Artist 01Unity Surface Shader for Artist 01
Unity Surface Shader for Artist 01
 
Pixel shaders
Pixel shadersPixel shaders
Pixel shaders
 

Similaire à Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks

Introduction to open gl in android droidcon - slides
Introduction to open gl in android   droidcon - slidesIntroduction to open gl in android   droidcon - slides
Introduction to open gl in android droidcon - slides
tamillarasan
 
Minko stage3d workshop_20130525
Minko stage3d workshop_20130525Minko stage3d workshop_20130525
Minko stage3d workshop_20130525
Minko3D
 
Opengl lec 3
Opengl lec 3Opengl lec 3
Opengl lec 3
elnaqah
 
I need help with this assignment Ive gotten abit stuck with the cod.pdf
I need help with this assignment Ive gotten abit stuck with the cod.pdfI need help with this assignment Ive gotten abit stuck with the cod.pdf
I need help with this assignment Ive gotten abit stuck with the cod.pdf
Conint29
 

Similaire à Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks (20)

ShaderX³: Geometry Manipulation - Morphing between two different objects
ShaderX³: Geometry Manipulation - Morphing between two different objectsShaderX³: Geometry Manipulation - Morphing between two different objects
ShaderX³: Geometry Manipulation - Morphing between two different objects
 
openFrameworks 007 - GL
openFrameworks 007 - GL openFrameworks 007 - GL
openFrameworks 007 - GL
 
Implementing a modern, RenderMan compliant, REYES renderer
Implementing a modern, RenderMan compliant, REYES rendererImplementing a modern, RenderMan compliant, REYES renderer
Implementing a modern, RenderMan compliant, REYES renderer
 
Vertex Shader Tricks by Bill Bilodeau - AMD at GDC14
Vertex Shader Tricks by Bill Bilodeau - AMD at GDC14Vertex Shader Tricks by Bill Bilodeau - AMD at GDC14
Vertex Shader Tricks by Bill Bilodeau - AMD at GDC14
 
Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019
 
Introduction to open gl in android droidcon - slides
Introduction to open gl in android   droidcon - slidesIntroduction to open gl in android   droidcon - slides
Introduction to open gl in android droidcon - slides
 
Rendering basics
Rendering basicsRendering basics
Rendering basics
 
TransNeRF
TransNeRFTransNeRF
TransNeRF
 
Post rendering
Post renderingPost rendering
Post rendering
 
NvFX GTC 2013
NvFX GTC 2013NvFX GTC 2013
NvFX GTC 2013
 
Cg in Two Pages
Cg in Two PagesCg in Two Pages
Cg in Two Pages
 
GL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdfGL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdf
 
Minko stage3d workshop_20130525
Minko stage3d workshop_20130525Minko stage3d workshop_20130525
Minko stage3d workshop_20130525
 
The Technology behind Shadow Warrior, ZTG 2014
The Technology behind Shadow Warrior, ZTG 2014The Technology behind Shadow Warrior, ZTG 2014
The Technology behind Shadow Warrior, ZTG 2014
 
【Unite 2017 Tokyo】シェーダープログラミング入門!カスタムシェーダー、作るで!
【Unite 2017 Tokyo】シェーダープログラミング入門!カスタムシェーダー、作るで!【Unite 2017 Tokyo】シェーダープログラミング入門!カスタムシェーダー、作るで!
【Unite 2017 Tokyo】シェーダープログラミング入門!カスタムシェーダー、作るで!
 
Game Programming 12 - Shaders
Game Programming 12 - ShadersGame Programming 12 - Shaders
Game Programming 12 - Shaders
 
Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5
 
Opengl lec 3
Opengl lec 3Opengl lec 3
Opengl lec 3
 
OpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsOpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI Platforms
 
I need help with this assignment Ive gotten abit stuck with the cod.pdf
I need help with this assignment Ive gotten abit stuck with the cod.pdfI need help with this assignment Ive gotten abit stuck with the cod.pdf
I need help with this assignment Ive gotten abit stuck with the cod.pdf
 

Plus de JinTaek Seo

Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeksBeginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
JinTaek Seo
 

Plus de JinTaek Seo (14)

Neural network 20161210_jintaekseo
Neural network 20161210_jintaekseoNeural network 20161210_jintaekseo
Neural network 20161210_jintaekseo
 
05 heap 20161110_jintaeks
05 heap 20161110_jintaeks05 heap 20161110_jintaeks
05 heap 20161110_jintaeks
 
02 linked list_20160217_jintaekseo
02 linked list_20160217_jintaekseo02 linked list_20160217_jintaekseo
02 linked list_20160217_jintaekseo
 
Hermite spline english_20161201_jintaeks
Hermite spline english_20161201_jintaeksHermite spline english_20161201_jintaeks
Hermite spline english_20161201_jintaeks
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
03 fsm how_toimplementai_state_20161006_jintaeks
03 fsm how_toimplementai_state_20161006_jintaeks03 fsm how_toimplementai_state_20161006_jintaeks
03 fsm how_toimplementai_state_20161006_jintaeks
 
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeksBeginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
Beginning direct3d gameprogrammingmath01_primer_20160324_jintaeks
 
Boost pp 20091102_서진택
Boost pp 20091102_서진택Boost pp 20091102_서진택
Boost pp 20091102_서진택
 
아직도가야할길 훈련 20090722_서진택
아직도가야할길 훈련 20090722_서진택아직도가야할길 훈련 20090722_서진택
아직도가야할길 훈련 20090722_서진택
 
3ds maxscript 튜토리얼_20151206_서진택
3ds maxscript 튜토리얼_20151206_서진택3ds maxscript 튜토리얼_20151206_서진택
3ds maxscript 튜토리얼_20151206_서진택
 
Multithread programming 20151206_서진택
Multithread programming 20151206_서진택Multithread programming 20151206_서진택
Multithread programming 20151206_서진택
 
03동물 로봇그리고사람 public_20151125_서진택
03동물 로봇그리고사람 public_20151125_서진택03동물 로봇그리고사람 public_20151125_서진택
03동물 로봇그리고사람 public_20151125_서진택
 
20150605 홀트입양예비부모모임 서진택
20150605 홀트입양예비부모모임 서진택20150605 홀트입양예비부모모임 서진택
20150605 홀트입양예비부모모임 서진택
 
Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택
 

Dernier

"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 

Dernier (20)

Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 

Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks

  • 1. Beginning Direct3D Game Programming: 9. Shader Programming jintaeks@gmail.com Division of Digital Contents, DongSeo University. May 2016
  • 2. Shaders  Vertex shaders are executable programs that process vertex data.  In the fixed function pipeline, Vertex processing takes primitive vertex data from model space and converts it into vertex data in projection space. 2
  • 3. Vertex Processing  Vertex processing converts data from model space to projection space. 3
  • 4. Vertex Blending  Blending combines one or more sets of vertex data to animate vertex data.  Vertex blending uses one set of vertex data and one or more transforms (each with a corresponding weight). 4
  • 5. Primitive Processing  After vertex processing, primitive processing and pixel processing convert per-vertex data into the final pixels that will be rendered. 5
  • 6. ■ Clipping. Clipping or removing geometry that’s outside of the viewing frustum to maximize rendering efficiency. ■ Homogeneous divide. Converting the x,y,z vertex data to nonhomogeneous space before sending the data to the rasterizer. ■ Viewport scaling. Scaling 2-D projection space to 2-D screen space. ■ Triangle set up. Preparing triangle-attribute interpolators and converting per-vertex attributes into per-pixel attributes. 6
  • 7. Pixel Processing  The output of primitive processing is vertex data interpolated per pixel.  Pixel processing blends several per-pixel data types and texture samples (if any) into output pixel colors. 7
  • 8. Part 1 ■ Sample texture. Sample one or more textures. ■ Blend. Blend per-pixel attributes, typically diffuse and specular color and/or texture samples. 8
  • 9. Part 2 ■ Alpha test. Apply an alpha test to see if the pixel color will affect the final pixel color. ■ Depth test. Update the depth buffer with the pixel depth if the pixel is visible. ■ Stencil test. Apply a stencil test to see if the pixel will affect the final pixel color. ■ Per-pixel fog. Apply a fog color to the pixel color. ■ Alpha blend. Apply pixel alpha to create a transparent or semitransparent blend between a source pixel and a frame buffer pixel. ■ Dither. Use a dithering algorithm to blend adjacent pixels for a more consistent color range. ■ Gamma. Apply a gamma correction to the final frame buffer pixel color. 9
  • 11. ■ Texture data. Texture resources such as a texture file or a render target. ■ Sampler. Used to sample textures, which means to use the texture coordinates to look up a texture color. – Texture filtering influences the quality of the information (typically color) that is sampled from a texture. 11
  • 12. Programmable Shader  Assembly Shader in DirectX 8. 12
  • 13. HLSL: High-Level Shading Language  HLSL is a shading language developed by Microsoft for the Direct3D 9 API to augment the shader assembly language.  HLSL is analogous to the GLSL shading language used with the OpenGL standard. It is very similar to the Nvidia Cg shading language.  HLSL programs come in five forms: – pixel shaders (fragment in GLSL) – vertex shaders – geometry shaders – compute shaders – tessellation shaders (Hull and Domain shaders). 13
  • 14. Vertex Shader Comparison  VS 2.0 = DirectX 9.0 original Shader Model 2 specification.  VS 2.0a = NVIDIA GeForce FX/PCX-optimized model, DirectX 9.0a.  VS 3.0 = Shader Model 3.0, DirectX 9.0c.  VS 4.0 = Shader Model 4.0, DirectX 10.  VS 4.1 = Shader Model 4.1, DirectX 10.1.  VS 5.0 = Shader Model 5.0, DirectX 11. 14
  • 15. 15
  • 16. Vertex Shader Example VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, float3 vNormal : NORMAL, float2 vTexCoord0 : TEXCOORD0 ) { VS_OUTPUT Output; float3 vNormalWorldSpace; float4 vAnimatedPos = vPos; // Transform the position from object space to homogeneous projection space Output.Position = mul(vAnimatedPos, g_mWorldViewProjection); // Transform the normal from object space to world space vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // Compute simple directional lighting equation float3 vTotalLightDiffuse = float3(0,0,0); vTotalLightDiffuse += g_LightDiffuse * max( 0, dot( vNormalWorldSpace, g_LightDir ) ); 16
  • 17. VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, float3 vNormal : NORMAL, float2 vTexCoord0 : TEXCOORD0 ) { … // Compute simple directional lighting equation float3 vTotalLightDiffuse = float3(0,0,0); vTotalLightDiffuse += g_LightDiffuse * max( 0, dot( vNormalWorldSpace, g_LightDir ) ); Output.Diffuse.rgb = g_MaterialDiffuseColor * vTotalLightDiffuse + g_MaterialAmbientColor * g_LightAmbient; Output.Diffuse.a = 1.0f; // Just copy the texture coordinate through Output.TextureUV = vTexCoord0; return Output; } 17
  • 18. Pixel Shader Comparison  PS 2.0 = DirectX 9.0 original Shader Model 2 specification.  PS 2.0a = NVIDIA GeForce FX/PCX-optimized model, DirectX 9.0a.  PS 2.0b = ATI Radeon X700, X800, X850, FireGL X3-256, V5000, V5100 and V7100 shader model, DirectX 9.0b.  PS 3.0 = Shader Model 3.0, DirectX 9.0c.  PS 4.0 = Shader Model 4.0, DirectX 10.  PS 4.1 = Shader Model 4.1, DirectX 10.1.  PS 5.0 = Shader Model 5.0, DirectX 11. 18
  • 19. 19
  • 20. Pixel Shader Example struct VS_OUTPUT { float4 Position : POSITION; // vertex position float4 Diffuse : COLOR0; // vertex diffuse color (note that COLOR0 is clamped from 0..1) float2 TextureUV : TEXCOORD0; // vertex texture coords }; PS_OUTPUT RenderScenePS( VS_OUTPUT In ) { PS_OUTPUT Output; // Lookup mesh texture and modulate it with diffuse Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse; return Output; } 20
  • 21. Effects(Direct3D 9)  A Microsoft DirectX effect enables the integration of vertex and pixel shaders with pipeline state to render objects.  Effects also provide a convenient way to write shaders for different hardware versions.  An effect can replace the vertex processing and part of the pixel processing performed by the graphics pipeline. 21
  • 22. Effects and the 3D Pipeline  Vertex and pixel processing can be performed by the fixed function pipeline, or can be implemented with programmable shaders.  The input data tessellation, primitive processing, and data outputs are controlled by pipeline state. All this can be integrated into an effect. 22
  • 23. Effects can save and restore states  Shader state. – This includes creating and deleting shaders, setting shader constants, setting shader state, and rendering with shaders.  Texture and sampler state. – This includes specifying texture files, initializing texture stages, creating sampler objects, and setting sampler state.  Other pipeline state. – This includes states for setting transformations, lighting, materials, and rendering options.  All rendering in an effect is done within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls. 23
  • 24. Effect State  Effect state initializes the pipeline for processing pipeline data. Effect variables hold effect state values. technique TVertexShaderOnly_Asm { pass P0 { // lighting Lighting = FALSE; SpecularEnable = TRUE; // samplers Sampler[0] = (Sampler); // texture stages ColorOp[0] = MODULATE; ColorArg1[0] = TEXTURE; ColorArg2[0] = DIFFUSE; AlphaOp[0] = MODULATE; 24
  • 25. Writing an Effect  Writing an effect requires that you understand effect syntax, and generate the required state information.  An effect is typically encapsulated into an effect file (.fx) but could also be written as a text string in an application. 25
  • 26. Simple Effect Example // texture texture Tex0 < string name = "tiger.bmp"; >; sampler Sampler = sampler_state { Texture = (Tex0); MipFilter = LINEAR; MinFilter = LINEAR; MagFilter = LINEAR; }; float4x4 matWorldViewProj : WORLDVIEWPROJ; struct VS_OUTPUT { float4 Pos : POSITION; float2 Tex : TEXCOORD0; }; 26
  • 27. VS_OUTPUT VS( float3 Pos : POSITION, float2 Tex : TEXCOORD0) { VS_OUTPUT Out = (VS_OUTPUT)0; Out.Pos = mul(Pos, matWorldViewProj); Out.Tex = Tex; return Out; } technique TVertexShaderOnly_HLSL { pass P0 { // lighting Lighting = FALSE; SpecularEnable = TRUE; // samplers Sampler[0] = (Sampler); // texture stages ColorOp[0] = MODULATE; 27
  • 28. // texture stages ColorOp[0] = MODULATE; ColorArg1[0] = TEXTURE; ColorArg2[0] = DIFFUSE; AlphaOp[0] = MODULATE; AlphaArg1[0] = TEXTURE; AlphaArg2[0] = DIFFUSE; ColorOp[1] = DISABLE; AlphaOp[1] = DISABLE; // shaders VertexShader = compile vs_1_1 VS(); PixelShader = NULL; } } 28
  • 29. Effect Example: BasicHLSL sample in DirectX Sdk //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- float4 g_MaterialAmbientColor; // Material's ambient color float4 g_MaterialDiffuseColor; // Material's diffuse color float3 g_LightDir; // Light's direction in world space float4 g_LightDiffuse; // Light's diffuse color float4 g_LightAmbient; // Light's ambient color texture g_MeshTexture; // Color texture for mesh float g_fTime; // App's time in seconds float4x4 g_mWorld; // World matrix for object float4x4 g_mWorldViewProjection; // World * View * Projection matrix 29
  • 30. Texture samplers, Vertex shader output structure //-------------------------------------------------------------------------------------- // Texture samplers //-------------------------------------------------------------------------------------- sampler MeshTextureSampler = sampler_state { Texture = <g_MeshTexture>; MipFilter = LINEAR; MinFilter = LINEAR; MagFilter = LINEAR; }; //-------------------------------------------------------------------------------------- // Vertex shader output structure //-------------------------------------------------------------------------------------- struct VS_OUTPUT { float4 Position : POSITION; // vertex position float4 Diffuse : COLOR0; // vertex diffuse color (note that COLOR0 is clamped from 0..1) float2 TextureUV : TEXCOORD0; // vertex texture coords }; 30
  • 31. Vertex shader //-------------------------------------------------------------------------------------- // This shader computes standard transform and lighting //-------------------------------------------------------------------------------------- VS_OUTPUT RenderSceneVS( float4 vPos : POSITION, float3 vNormal : NORMAL, float2 vTexCoord0 : TEXCOORD0, uniform int nUnused, uniform bool bTexture, uniform bool bAnimate ) { VS_OUTPUT Output; float3 vNormalWorldSpace; float4 vAnimatedPos = vPos; // Transform the position from object space to homogeneous projection space Output.Position = mul(vAnimatedPos, g_mWorldViewProjection); // Transform the normal from object space to world space vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space) 31
  • 32. // Transform the normal from object space to world space vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space) // Compute simple directional lighting equation float3 vTotalLightDiffuse = float3(0,0,0); vTotalLightDiffuse += g_LightDiffuse * max( 0, dot( vNormalWorldSpace, g_LightDir ) ); Output.Diffuse.rgb = g_MaterialDiffuseColor * vTotalLightDiffuse + g_MaterialAmbientColor * g_LightAmbient; Output.Diffuse.a = 1.0f; // Just copy the texture coordinate through if( bTexture ) Output.TextureUV = vTexCoord0; else Output.TextureUV = 0; return Output; } 32
  • 33. Pixel shader // Pixel shader output structure struct PS_OUTPUT { float4 RGBColor : COLOR0; // Pixel color }; // This shader outputs the pixel's color by modulating the texture's // color with diffuse material color //-------------------------------------------------------------------------------------- PS_OUTPUT RenderScenePS( VS_OUTPUT In, uniform bool bTexture ) { PS_OUTPUT Output; // Lookup mesh texture and modulate it with diffuse if( bTexture ) Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse; else Output.RGBColor = In.Diffuse; return Output; } 33
  • 34. technique //-------------------------------------------------------------------------------------- // Renders scene to render target //-------------------------------------------------------------------------------------- technique RenderSceneWithTexture1Light { pass P0 { VertexShader = compile vs_2_0 RenderSceneVS( 1, false, false ); PixelShader = compile ps_2_0 RenderScenePS( false ); // trivial pixel shader (could use FF instead if desired) } } technique RenderSceneWithTexture2Light { pass P0 { VertexShader = compile vs_2_0 RenderSceneVS( 2, true, true ); PixelShader = compile ps_2_0 RenderScenePS( true ); // trivial pixel shader (could use FF instead if desired) } }34
  • 35. Effects Contain One or More Techniques and Passes technique T0 { pass P0 { ... } } technique T1 { pass P0 { ... } pass P1 { ... } } 35
  • 36. Using an Effect: Creating an Effect ID3DXEffect* g_pEffect = NULL; DWORD dwShaderFlags = 0; dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; dwShaderFlags |= D3DXSHADER_NO_PRESHADER; // Read the D3DX effect file WCHAR str[MAX_PATH]; DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL.fx" ); D3DXCreateEffectFromFile( pd3dDevice, str, NULL, // CONST D3DXMACRO* pDefines, NULL, // LPD3DXINCLUDE pInclude, dwShaderFlags, NULL, // LPD3DXEFFECTPOOL pPool, &g_pEffect, NULL ); 36
  • 37. Render an Effect // Apply the technique contained in the effect g_pEffect->Begin(&cPasses, 0); for (iPass = 0; iPass < cPasses; iPass++) { g_pEffect->BeginPass(iPass); // Only call CommitChanges if any state changes have happened // after BeginPass is called g_pEffect->CommitChanges(); // Render the mesh with the applied technique g_pMesh->DrawSubset(0); g_pEffect->EndPass(); } g_pEffect->End(); 37
  • 38. Use Semantics to Find Effect Parameters  In effect file, the semantic is located following a colon (:) after the parameter name. For instance: float4x4 matWorldViewProj : WORLDVIEWPROJ;  The effect interface can use a semantic to get a handle to a particular effect parameter. For instance: D3DHANDLE handle = m_pEffect->GetParameterBySemantic(NULL, "WORLDVIEWPROJ"); 38
  • 39. Add Parameter Information with Annotations  Annotations are user-specific data that can be attached to any technique, pass, or parameter. – An annotation is a flexible way to add information to individual parameters.  Annotation declarations are delimited by angle brackets. An annotation contains: – A data type. – A variable name. – An equals sign (=). – The data value. – A ending semicolon (;). texture Tex0 < string name = "tiger.bmp"; >; 39
  • 40. texture Tex0 < string name = "tiger.bmp"; >;  The annotation is attached to the texture object and specifies the texture file that should be used to initialize the texture object.  The annotation does not initialize the texture object, it is simply a piece of user information.  An application can read the annotation with ID3DXBaseEffect::GetAnnotation. 40
  • 41. Set Effect Parameters m_pEffect->SetTechnique( "RenderScene" ); m_pEffect->BeginParameterBlock(); D3DXVECTOR4 v4( Diffuse.r, Diffuse.g, Diffuse.b, Diffuse.a ); m_pEffect->SetVector( "g_vDiffuse", &v4 ); m_pEffect->SetFloat( "g_fReflectivity", fReflectivity ); m_pEffect->SetFloat( "g_fAnimSpeed", fAnimSpeed ); m_pEffect->SetFloat( "g_fSizeMul", fSize ); m_hParameters = m_pEffect->EndParameterBlock(); 41
  • 42. Practice: Build BasicHLSL sample project in Sdk  Examine all statements related to 'g_pEffect'. ID3DXEffect* g_pEffect = NULL; // D3DX effect interface  Examine all statements in the effect file related to 'g_pEffect'. 42
  • 44.  Replace 'tiny.x' mesh with 'teapot.x'  Disable the vertex animation in effect file.  Modify diffuse color of lights and check the result. 44
  • 45. References  Kris Gray, "DirectX 9 Programmable Graphics Pipeline", Microsoft Press. 45