SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PPTX
Beyond porting
Cass Everitt
 
PPT
CS 354 Understanding Color
Mark Kilgard
 
PDF
OpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
Tristan Lorach
 
PPT
CS 354 Blending, Compositing, Anti-aliasing
Mark Kilgard
 
PPT
CS 354 Transformation, Clipping, and Culling
Mark Kilgard
 
PDF
Project Fortress
Alex Miller
 
PPT
CS 354 Graphics Math
Mark Kilgard
 
PPTX
FlameWorks GTC 2014
Simon Green
 
PPT
CS 354 Pixel Updating
Mark Kilgard
 
PPSX
Advancements in-tiled-rendering
mistercteam
 
PPTX
Trident International Graphics Workshop 2014 5/5
Takao Wada
 
PPTX
Rethinking Attention with Performers
Joonhyung Lee
 
PPT
CS 354 More Graphics Pipeline
Mark Kilgard
 
PDF
Modern OpenGL Usage: Using Vertex Buffer Objects Well
Mark Kilgard
 
PDF
Foreground detection using gaussian mixture models matlab
ym.ygrex@comp
 
PPT
CS 354 Viewing Stuff
Mark Kilgard
 
PPSX
Dx11 performancereloaded
mistercteam
 
PPTX
ARCHITECTURAL CONDITIONING FOR DISENTANGLEMENT OF OBJECT IDENTITY AND POSTURE...
홍배 김
 
PPT
CS 354 Acceleration Structures
Mark Kilgard
 
Beyond porting
Cass Everitt
 
CS 354 Understanding Color
Mark Kilgard
 
OpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
Tristan Lorach
 
CS 354 Blending, Compositing, Anti-aliasing
Mark Kilgard
 
CS 354 Transformation, Clipping, and Culling
Mark Kilgard
 
Project Fortress
Alex Miller
 
CS 354 Graphics Math
Mark Kilgard
 
FlameWorks GTC 2014
Simon Green
 
CS 354 Pixel Updating
Mark Kilgard
 
Advancements in-tiled-rendering
mistercteam
 
Trident International Graphics Workshop 2014 5/5
Takao Wada
 
Rethinking Attention with Performers
Joonhyung Lee
 
CS 354 More Graphics Pipeline
Mark Kilgard
 
Modern OpenGL Usage: Using Vertex Buffer Objects Well
Mark Kilgard
 
Foreground detection using gaussian mixture models matlab
ym.ygrex@comp
 
CS 354 Viewing Stuff
Mark Kilgard
 
Dx11 performancereloaded
mistercteam
 
ARCHITECTURAL CONDITIONING FOR DISENTANGLEMENT OF OBJECT IDENTITY AND POSTURE...
홍배 김
 
CS 354 Acceleration Structures
Mark Kilgard
 

Viewers also liked (20)

PPTX
Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming01_20161102_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogramming07_lightsandmaterials_20161117_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
JinTaek Seo
 
PPTX
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
JinTaek Seo
 
PDF
Shaders - Claudia Doppioslash - Unity With the Best
BeMyApp
 
PPTX
Writing shaders - YOU can do it!
Nordeus
 
PPTX
Shader Programming With Unity
Mindstorm Studios
 
PDF
Unity Surface Shader for Artist 01
SangYun Yi
 
PPTX
Pixel shaders
buds nan kis
 
Beginning direct3d gameprogrammingmath06_transformations_20161019_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogramming02_overviewofhalandcom_20160408_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogramming04_3dfundamentals_20160414_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogrammingmath04_calculus_20160324_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogramming01_20161102_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogramming01_thehistoryofdirect3dgraphics_20160407_ji...
JinTaek Seo
 
Beginning direct3d gameprogramming03_programmingconventions_20160414_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogrammingmath03_vectors_20160328_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogramming08_usingtextures_20160428_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogramming07_lightsandmaterials_20161117_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogrammingmath02_logarithm_20160324_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
JinTaek Seo
 
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
JinTaek Seo
 
Shaders - Claudia Doppioslash - Unity With the Best
BeMyApp
 
Writing shaders - YOU can do it!
Nordeus
 
Shader Programming With Unity
Mindstorm Studios
 
Unity Surface Shader for Artist 01
SangYun Yi
 
Pixel shaders
buds nan kis
 
Ad

Similar to Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks (20)

PDF
Minko stage3d workshop_20130525
Minko3D
 
PPT
Hardware Shaders
gueste52f1b
 
PDF
iOS Visual F/X Using GLSL
Douglass Turner
 
PDF
XNA L10–Shaders Part 1
Mohammad Shaker
 
PDF
Shaders in Unity
Matias Lavik
 
PPTX
Introduce to 3d rendering engine
Daosheng Mu
 
PDF
Game Programming 12 - Shaders
Nick Pruehs
 
PPT
D3 D10 Unleashed New Features And Effects
Thomas Goddard
 
PPTX
Shaders & Standard Shader In Unity
Ehsan Ehrari
 
PDF
Rendering basics
icedmaster
 
PPT
CS 354 GPU Architecture
Mark Kilgard
 
PPTX
Trident International Graphics Workshop 2014 1/5
Takao Wada
 
PPTX
Sig13 ce future_gfx
Cass Everitt
 
PPTX
Cg shaders with Unity3D
Michael Ivanov
 
PDF
PG-4034, Using OpenGL and DirectX for Heterogeneous Compute, by Karl Hillesland
AMD Developer Central
 
PPT
Next generation graphics programming on xbox 360
VIKAS SINGH BHADOURIA
 
PPT
Programmable Piplelines
Syed Zaid Irshad
 
PPTX
NvFX GTC 2013
Tristan Lorach
 
PPT
Introduction to 3D and shaders
Victor Porof
 
Minko stage3d workshop_20130525
Minko3D
 
Hardware Shaders
gueste52f1b
 
iOS Visual F/X Using GLSL
Douglass Turner
 
XNA L10–Shaders Part 1
Mohammad Shaker
 
Shaders in Unity
Matias Lavik
 
Introduce to 3d rendering engine
Daosheng Mu
 
Game Programming 12 - Shaders
Nick Pruehs
 
D3 D10 Unleashed New Features And Effects
Thomas Goddard
 
Shaders & Standard Shader In Unity
Ehsan Ehrari
 
Rendering basics
icedmaster
 
CS 354 GPU Architecture
Mark Kilgard
 
Trident International Graphics Workshop 2014 1/5
Takao Wada
 
Sig13 ce future_gfx
Cass Everitt
 
Cg shaders with Unity3D
Michael Ivanov
 
PG-4034, Using OpenGL and DirectX for Heterogeneous Compute, by Karl Hillesland
AMD Developer Central
 
Next generation graphics programming on xbox 360
VIKAS SINGH BHADOURIA
 
Programmable Piplelines
Syed Zaid Irshad
 
NvFX GTC 2013
Tristan Lorach
 
Introduction to 3D and shaders
Victor Porof
 
Ad

More from JinTaek Seo (14)

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

Recently uploaded (20)

PDF
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
PPTX
Work at Height training for workers .pptx
cecos12
 
PPSX
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
PPTX
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
PPTX
Mobile database systems 20254545645.pptx
herosh1968
 
PDF
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
PDF
Rapid Prototyping for XR: Lecture 4 - High Level Prototyping.
Mark Billinghurst
 
PDF
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
PPTX
CST413 KTU S7 CSE Machine Learning Neural Networks and Support Vector Machine...
resming1
 
PDF
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
PDF
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
PPTX
MATERIAL SCIENCE LECTURE NOTES FOR DIPLOMA STUDENTS
SAMEER VISHWAKARMA
 
PDF
PRIZ Academy - Process functional modelling
PRIZ Guru
 
PPTX
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
PPT
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
PPTX
Kel.3_A_Review_on_Internet_of_Things_for_Defense_v3.pptx
Endang Saefullah
 
PPTX
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
PPTX
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
PPTX
WHO And BIS std- for water quality .pptx
dhanashree78
 
PDF
Plant Control_EST_85520-01_en_AllChanges_20220127.pdf
DarshanaChathuranga4
 
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
Work at Height training for workers .pptx
cecos12
 
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
Mobile database systems 20254545645.pptx
herosh1968
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
Rapid Prototyping for XR: Lecture 4 - High Level Prototyping.
Mark Billinghurst
 
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
CST413 KTU S7 CSE Machine Learning Neural Networks and Support Vector Machine...
resming1
 
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
MATERIAL SCIENCE LECTURE NOTES FOR DIPLOMA STUDENTS
SAMEER VISHWAKARMA
 
PRIZ Academy - Process functional modelling
PRIZ Guru
 
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
Kel.3_A_Review_on_Internet_of_Things_for_Defense_v3.pptx
Endang Saefullah
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
WHO And BIS std- for water quality .pptx
dhanashree78
 
Plant Control_EST_85520-01_en_AllChanges_20220127.pdf
DarshanaChathuranga4
 

Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks

  • 1. Beginning Direct3D Game Programming: 9. Shader Programming [email protected] 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