03 Basic Direct3D Programming
03 Basic Direct3D Programming
Contents
Direct3D concepts
Device Resource
Device
Gateway to Direct3D functionalities Abstraction of one or more physical devices
Allocates and destroys objects Renders primitives Communicates with graphics driver and hardware
D3D11CreateDevice Function
Syntax
HRESULT D3D11CreateDevice( __in IDXGIAdapter* pAdapter, __in D3D_DRIVER_TYPE DriverType, __in HMODULE Software, __in UINT Flags, __in const D3D_FEATURE_LEVEL* pFeatureLevels, __in UINT FeatureLevels, __in UINT SDKVersion, __out ID3D11Device** ppDevice, __out D3D_FEATURE_LEVEL* pFeatureLevel, __out ID3D11DeviceContext** ppImmediateContext );
Example
ID3D11Device* pDev = NULL; ID3D11DeviceContext* pDevImmCtx = NULL; hr = D3D11CreateDevice( &pDev, &pDevImmCtx ); pDevImmCtx->Release(); pDev->Release();
D3D11CreateDeviceAndSwapChain Function
Syntax
HRESULT D3D11CreateDeviceAndSwapChain( __in IDXGIAdapter *pAdapter, __in D3D_DRIVER_TYPE DriverType, __in HMODULE Software, __in UINT Flags, __in const D3D_FEATURE_LEVEL *pFeatureLevels, __in UINT FeatureLevels, __in UINT SDKVersion, __in const DXGI_SWAP_CHAIN_DESC *pSwapChainDesc, __out IDXGISwapChain **ppSwapChain, __out ID3D11Device **ppDevice, __out D3D_FEATURE_LEVEL *pFeatureLevel, __out ID3D11DeviceContext **ppImmediateContext );
Example
ID3D11Device* pDev = NULL; ID3D11DeviceContext* pDevImmCtx = NULL; IDXGISwapChain* pSwapChain = NULL; hr = D3D11CreateDevice( &pSwapChain, &pDev, , &pDevImmCtx ); pSwapChain->Release(); pDevImmCtx->Release(); pDev->Release();
IDXGIFactory::CreateSwapChain
After creating swap chain, call D3D11CreateDevice to create device
Feature Level
Direct3D 11 applications can run on a downlevel hardware D3D_FEATURE_LEVEL enumeration
enum D3D_FEATURE_LEVEL { D3D_FEATURE_LEVEL_9_1 D3D_FEATURE_LEVEL_9_2 D3D_FEATURE_LEVEL_9_3 D3D_FEATURE_LEVEL_10_0 D3D_FEATURE_LEVEL_10_1 D3D_FEATURE_LEVEL_11_0 }; = = = = = = 0x9100, 0x9200, 0x9300, 0xa000, 0xa100, 0xb000
ID3D11Device Interface
Classification Creation of resources Creation of resource views Methods CreateBuffer CreateTexture1D / CreateTexture2D / CreateTexture3D CreateShaderResourceView CreateRenderTargetView CreateDepthStencilView CreateUnorderedAccessView CreateInputLayout CreateRasterizerState CreateDepthStencilState CreateBlendState CreateSamplerState CreateVertexShader CreateGeometryShader CreatePixelShader GetImmediateContext CreateDeferredContext
Device Context
Contains circumstances or setting in which device is used for rendering
Gets and sets pipeline state Supplies resources owned by device to pipeline Generates rendering commands (Draw functions)
Two types
Immediate context and deferred context Both are represented by ID3D11DeviceContext interface
Immediate Context
Rendering commands directly issued to driver
As soon as rendering methods are called
One and only one immediate context for each device The only device context for single-threaded applications Obtained along with device creation or from ID3D11Device::GetImmediateContext function
ID3D11DeviceContext
Classification
Restoring all default settings Clearing resources Copying and accessing resource data
Methods
ClearState ClearRenderTargetView ClearDepthStencilView CopyResource / CopySubresourceRegion UpdateSubresource Map / Unmap IASetVertexBuffers IASetIndexBuffers IASetInputLayout IASetPrimitiveTopology [VS]SetShader [VS]SetConstantBuffers [VS]SetShaderResources [VS]SetSamplers CSSetUnorderedAccessViews RSSetViewports RSSetScissorRects RSSetState OMSetDepthStencilState OMSetBlendState OMSetRenderTargets Draw / DrawInstanced DrawIndexed / DrawIndexedInstanced
(not exhaustive)
Setting up IA stage
Setting up RS stage
Setting up OM stage
Rendering
Resource
Building blocks of scene
Area in memory accessed by Direct3D pipeline
Input geometry, shader resources, textures, Two categories: buffer and texture
Resource Types
Interfaces ID3D11Buffer ID3D11Texture1D ID3D11Texture2D ID3D11Texture3D Description Accesses buffer data Accesses data in 1D texture and 1D texture array Accesses data in 2D texture and 2D texture array Accesses data in 3D texture and 3D texture array
Description Data format Expected usage Binding to pipeline stages CPU accessibility Less common options
Description
32-bit floating-point format following IEEE 754 Unsigned integer (3-bit: 0, 1, 2, 3, 4, 5, 6, 7) Twos-complement signed integer (3-bit: -4, -3, -2, -1, 0, 1, 2, 3)
_UNORM
_SNORM _TYPELESS
Resource Usage
D3D11_USAGE enumeration
Identifies the way resource is intended to be used Reflects whether resource is accessible by GPU and/or CPU
Resource usage Default Immutable Dynamic Description Most common choice Cannot be changed after initialized Updates frequently (at least once per frame)
Staging
Usage GPU-Read GPU-Write CPU-Read CPU-Write
Can be bound as
Input to a stage Output from a stage
Default
Dynamic
Immutable
Staging
Creating Buffer
1) Fill D3D11_BUFFER_DESC structure
typedef struct D3D11_BUFFER_DESC { UINT ByteWidth; D3D11_USAGE Usage; UINT BindFlags; UINT CPUAccessFlags; UINT MiscFlags; UINT StructureByteStride; } D3D11_BUFFER_DESC;
Resource View
Pipeline stage interprets resource data using resource view
Dictates the role resource is bound to pipeline with Conceptually similar to casting data Specifies data format of typeless resource
Resource interface ID3D11ShaderResourceView ID3D11RenderTargetView ID3D11DepthStencilView ID3D11UnorderedAccessView Description Access shader resource such as constant buffer, texture, or sampler Access texture resource that is used as render-target Access texture during depth-stencil testing Access unordered resource using pixel/compute shader
typedef struct D3D11_RENDER_TARGET_VIEW_DESC { DXGI_FORMAT Format; D3D11_RTV_DIMENSION ViewDimension; union { D3D11_BUFFER_RTV Buffer; D3D11_TEX1D_RTV Texture1D; D3D11_TEX1D_ARRAY_RTV Texture1DArray; D3D11_TEX2D_RTV Texture2D; D3D11_TEX2D_ARRAY_RTV Texture2DArray; D3D11_TEX2DMS_RTV Texture2DMS; D3D11_TEX2DMS_ARRAY_RTV Texture2DMSArray; D3D11_TEX3D_RTV Texture3D; }; } D3D11_RENDER_TARGET_VIEW_DESC;
Functions
D3DXVec3Normalize, D3DXVec3Cross, D3DXMatrixTranspose, D3DXMatrixLookAtLH, D3DXMatrixRotationQuaternion,
D3DXVECTOR3 a(1,0,0), b(0,1,0); D3DXVECTOR3 x, y; x = a + b; D3DXVec3Normalize(&y, D3DXVec3Cross(&x, &a, &b));
XMMATRIX
Logical grouping of four SIMD hardware registers
XMVECTOR eye, focus, up; XMMATRIX view = XMMatrixLookAtLH(eye, focus, up); XMMATRIX tview = XMMatrixTranspose(view);
XMMATRIX world, proj; XMMATRIX wvp = world * view * proj;
Direct3D Programming
Setting up each pipeline stage
Setting up IA stage Setting up shader stages Setting up RS stage Configuring OM stage
HLSL programming
ID3D11Device Interface
Classification Creation of resources Creation of resource views Methods CreateBuffer CreateTexture1D / CreateTexture2D / CreateTexture3D CreateShaderResourceView CreateRenderTargetView CreateDepthStencilView CreateUnorderedAccessView CreateInputLayout CreateRasterizerState CreateDepthStencilState CreateBlendState CreateSamplerState CreateVertexShader CreateGeometryShader CreatePixelShader GetImmediateContext CreateDeferredContext
ID3D11DeviceContext
Classification
Restoring all default settings Clearing resources Copying and accessing resource data
Methods
ClearState ClearRenderTargetView ClearDepthStencilView CopyResource / CopySubresourceRegion UpdateSubresource Map / Unmap IASetVertexBuffers IASetIndexBuffers IASetInputLayout IASetPrimitiveTopology [VS]SetShader [VS]SetConstantBuffers [VS]SetShaderResources [VS]SetSamplers CSSetUnorderedAccessViews RSSetViewports RSSetScissorRects RSSetState OMSetDepthStencilState OMSetBlendState OMSetRenderTargets Draw / DrawInstanced DrawIndexed / DrawIndexedInstanced
(not exhaustive)
Setting up IA stage
Setting up RS stage
Setting up OM stage
Rendering
More Interfaces
Classification
Resource
Interfaces
ID3D11Buffer ID3D11Texture1D / ID3D11Texture2D / ID3D11Texture3D
Resource view
Pipeline state
Setting Up IA Stage
1) Create input buffers
One or more vertex buffers An index buffer (optional)
Setting Up RS Stage
1) Set viewport
Viewport maps vertex positions (in clip space) into render-target positions
Depth-Stencil Functionality
1) Create depth-stencil resource (2D texture)
DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_D24_UNORM_S8_UINT,
Blending Functionality
1) Create blend state
2) Bind blend state
Mappable resources
Process of giving CPU access to underlying memory Copying among non-mappable resources is very fast Mapping and copying among mappable resources should be done with care
// Create constant buffer D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( XMMATRIX ); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &pCBMatView ); if( FAILED( hr ) ) return hr; // Update constant buffer XMMATRIX matView; XMVECTOR vecEye = XMVectorSet( 0.0f, 1.0f, -5.0f, 0.0f ); XMVECTOR vecAt = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); XMVECTOR vecUp = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ); matView = XMMatrixLookAtLH( Eye, At, Up ); matView = XMMatrixTranspose( matView ); pImmediateContext->UpdateSubresource( pCBMatView, 0, NULL, &matView, 0, 0 );
Intrinsic Functions
Provides commonly used operations Efficient and tested use them if available
abs, acos, atan, atan2, ceil, clamp, cos, cosh, cross, degrees, determinant, distance, dot, exp, exp2, floor, fmod, frac, frexp, isfinite, isinf, isnan, length, lerp, lit, log, log10, log2, mad, max, min, modf, mul, noise, normalize, pow, radians, rcp, reversebits, round, rsqrt, saturate, sign, sin, sincos, sinh, sqrt, step, tan, tanh, transpose, trunc,
matrix World; matrix View; matrix Proj; float4 VS( float4 Pos ) { float4 Out; Out = mul( Pos, World ); Out = mul( Out, View ); Out = mul( Out, Proj ); return Out; // Out = Pos * World * View * Proj }
Semantics
String attached to shader input/output
Conveys information about intended use of parameter Required on all variables passed between shader stages
matrix World, View, Proj;
struct VS_INPUT { float4 Pos : POSITION; }; struct VS_OUTPUT { float4 Pos : SV_Position; }; VS_OUTPUT VS( VS_INPUT In ) { VS_OUTPUT Out = (VS_OUTPUT)0; Out.Pos = mul( In.Pos, World ); Out.Pos = mul( Out.Pos, View ); Out.Pos = mul( Out.Pos, Proj ); return Out; } matrix World, View, Proj; float4 VS( float4 Pos : POSITION ) : SV_Position { float4 Out; Out = mul( Pos, World ); Out = mul( Out, View ); Out = mul( Out, Proj ); return Out; // Out = Pos * World * View * Proj }
POSITION
NORMAL COLOR TEXCOORD Output POSITION NORMAL COLOR TEXCOORD
float4
float4 float4 float4 Type float4 float4 float4 float4
VPOS
COLOR TEXCOORD
float2
float4 float4
(not exhaustive)
System-Value Semantics
Available in Direct3D 10 and above Begins with SV_ prefix
SV_ClipDistance, SV_CullDistance, SV_Coverage, SV_Depth, SV_IsFrontFace, SV_Position, SV_RenderTargetArrayIndex, SV_SampleIndex, SV_Target, SV_ViewportArrayIndex, SV_InstanceID, SV_PrimitiveID, SV_VertexID,
SV_Depth
DEPTH
struct VS_OUTPUT { float4 Pos : SV_POSITION; float4 Color : COLOR0; }; VS_OUTPUT VS( float4 Pos : POSITION, float4 Color : COLOR ) { VS_OUTPUT output = (VS_OUTPUT)0; output.Pos = mul( Pos, World ); output.Pos = mul( output.Pos, View ); output.Pos = mul( output.Pos, Proj ); output.Color = Color; return output; }
// Create D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(ConstantBuffer); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; hr = pd3dDevice->CreateBuffer( &bd, NULL, &pConstantBuffer ); if( FAILED( hr ) ) return hr;
// Update ConstantBuffer cb; cb.mWorld = XMMatrixTranspose( g_World ); cb.mView = XMMatrixTranspose( g_View ); cb.mProj = XMMatrixTranspose( g_Proj ); pImmediateContext->UpdateSubresource( pConstantBuffer, 0, NULL, &cb, 0, 0 ); // Bind pImmediateContext->VSSetConstantBuffers( 0, 1, &pConstantBuffer );
VS_OUTPUT VS( float4 Pos : POSITION, float4 Color : COLOR ) { VS_OUTPUT output = (VS_OUTPUT)0; output.Pos = mul( Pos, World ); output.Pos = mul( output.Pos, View ); output.Pos = mul( output.Pos, Proj ); output.Color = Color; return output; }