Thinking Different




Tutorial 50 - 지연 쉐이딩



원문 : http://www.rastertek.com/dx11tut50.html



 이 튜토리얼에서는 DirectX 11, C ++ 및 HLSL을 사용하여 지연 쉐이딩을 구현하는데 필요한 기본 사항에 대해 설명합니다. 이 듀토리얼의 코드는 이전 듀토리얼의 코드를 기반으로 작성됩니다.


Deferred shading은 전통적인 렌더링을 복잡한 조명을 필요로 하는 쉐이더의 효율성을 향상 시키도록 설계된 2 단계 시스템으로 분할하는 프로세스입니다.


첫 번째 단계에서는 정점과 픽셀 쉐이더를 사용하여 평소와 같이 렌더링합니다. 그러나 픽셀 쉐이더의 목적은 완전히 다릅니다. 우리는 더 이상 픽셀 쉐이더를 사용하여 라이팅 계산을 수행하지 않고 백 버퍼에 컬러를 출력합니다. 대신 픽셀에 대한 정보 (법선, 텍스처 색상 등)를 렌더링에서 텍스처 버퍼로 출력합니다. 이제 첫 번째 스테이지의 픽셀 쉐이더 출력은 두 번째 스테이지의 텍스처 입력으로 사용할 수 있는 장면 정보로 가득 찬 2D 텍스처가 되었습니다.


두 번째 단계에서는 기존의 모든 3D 쉐이더를 다시 작성하여 첫 번째 스테이지의 렌더링에서 텍스쳐 출력으로 2D 포스트 프로세싱을 수행합니다. 또한 2D 후처리 작업을 수행하기 때문에 수천 개의 복잡한 3D 오브젝트로 가득찬 거대한 장면 대신 조명 방정식을 실행하는데 설정된 픽셀수가 있습니다. 따라서 장면에 수천 개의 조명이 있거나 각 객체에 몇 개의 다각형이 있는지 더 이상 중요하지 않습니다. 최종 2D 출력 픽셀에 대해서만 조명 방정식을 수행합니다.


따라서 지연 쉐이딩은 장면의 모든 단일 모델에 대한 정점 및 픽셀 셰이더에서 필요한 모든 종류의 계산을 제거합니다. 그리고 이러한 모든 복잡한 계산은 출력 데이터를 생성합니다. 출력 데이터는 일반적으로 도려내기 때문에 아무렇게나 폐기됩니다. 그래서 쉐이딩 방정식은 장면 크기, 조명 수 등에 관계없이 간단히 계산되고 기타 모든 비효율적인 부분들은 제거되었습니다. 이것은 실제로 복잡한 조명을 간단히 처리 할수 있을 뿐만 아니라 이미 2D 후 처리가 필요한 쉐이더를 단순화하고 결합할 수 있습니다.


계속 진행하려면 먼저 첫 번째 스테이지에 대한 지연 셰이더를 작성한 다음 기존 셰이더를 다시 작성하여 첫 번째 스테이지 텍스처를 입력으로 사용하고 2D 후 처리를 수행해야합니다. 이 튜토리얼에서는 간략히 하기 위해 원래 방향 라이트 쉐이더를 다시 작성하고 지연 쉐이더에 연결하는 방법을 보여줍니다.


새로운 DeferredBufferClass를 살펴봄으로써 코드 섹션을 시작할 것입니다.



DeferredBufferClass는 단 하나의 텍스처가 아니라 텍스처의 배열을 처리하기 위해 재작성된 텍스처 클래스에 대한 렌더링입니다. 지연 셰이더의 출력은 이 클래스의 텍스처 버퍼(렌더링 대상)에 쓰게됩니다.


Deferredbuffersclass.h


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#pragma once
 
/////////////
// DEFINES //
/////////////
const int BUFFER_COUNT = 2;
 
 
class DeferredBuffersClass
{
public:
    DeferredBuffersClass();
    DeferredBuffersClass(const DeferredBuffersClass&);
    ~DeferredBuffersClass();
 
    bool Initialize(ID3D11Device*intintfloatfloat);
    void Shutdown();
 
    void SetRenderTargets(ID3D11DeviceContext*);
    void ClearRenderTargets(ID3D11DeviceContext*floatfloatfloatfloat);
 
    ID3D11ShaderResourceView* GetShaderResourceView(int);
 
private:
    int m_textureWidth = 0;
    int m_textureHeight = 0;
    ID3D11Texture2D* m_renderTargetTextureArray[BUFFER_COUNT] = { 0, };
    ID3D11RenderTargetView* m_renderTargetViewArray[BUFFER_COUNT] = { 0, };
    ID3D11ShaderResourceView* m_shaderResourceViewArray[BUFFER_COUNT] = { 0, };
    ID3D11Texture2D* m_depthStencilBuffer = nullptr;
    ID3D11DepthStencilView* m_depthStencilView = nullptr;
    D3D11_VIEWPORT m_viewport;
};
cs



Deferredbuffersclass.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#include "stdafx.h"
#include "deferredbuffersclass.h"
 
 
DeferredBuffersClass::DeferredBuffersClass()
{
    for(int i=0; i<BUFFER_COUNT; i++)
    {
        m_renderTargetTextureArray[i] = 0;
        m_renderTargetViewArray[i] = 0;
        m_shaderResourceViewArray[i] = 0;
    }
 
    m_depthStencilBuffer = 0;
    m_depthStencilView = 0;
}
 
 
DeferredBuffersClass::DeferredBuffersClass(const DeferredBuffersClass& other)
{
}
 
 
DeferredBuffersClass::~DeferredBuffersClass()
{
}
 
 
bool DeferredBuffersClass::Initialize(ID3D11Device* device, int textureWidth, int textureHeight, float screenDepth,
 float screenNear)
{
    
    HRESULT result = S_OK;
 
    // 렌더 텍스처의 폭과 높이를 저장한다.
    m_textureWidth = textureWidth;
    m_textureHeight = textureHeight;
 
    // 렌더 타겟 텍스처 구조체를 초기화합니다.
    D3D11_TEXTURE2D_DESC textureDesc;
    ZeroMemory(&textureDesc, sizeof(textureDesc));
 
    // 렌더 타겟 텍스처 구조체를 설정합니다.
    textureDesc.Width = textureWidth;
    textureDesc.Height = textureHeight;
    textureDesc.MipLevels = 1;
    textureDesc.ArraySize = 1;
    textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    textureDesc.SampleDesc.Count = 1;
    textureDesc.Usage = D3D11_USAGE_DEFAULT;
    textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
    textureDesc.CPUAccessFlags = 0;
    textureDesc.MiscFlags = 0;
 
    // 렌더 타겟 텍스처를 만듭니다.
    for(int i=0; i<BUFFER_COUNT; i++)
    {
        result = device->CreateTexture2D(&textureDesc, NULL&m_renderTargetTextureArray[i]);
        if(FAILED(result))
        {
            return false;
        }
    }
 
    // 렌더 타겟 뷰의 구조체를 설정합니다.
    D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
    renderTargetViewDesc.Format = textureDesc.Format;
    renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
    renderTargetViewDesc.Texture2D.MipSlice = 0;
 
    // 렌더 타겟 뷰를 생성합니다.
    for(int i=0; i<BUFFER_COUNT; i++)
    {
        result = device->CreateRenderTargetView(m_renderTargetTextureArray[i], &renderTargetViewDesc,
 &m_renderTargetViewArray[i]);
        if(FAILED(result))
        {
            return false;
        }
    }
 
    // 셰이더 리소스 뷰의 구조체를 설정합니다.
    D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
    shaderResourceViewDesc.Format = textureDesc.Format;
    shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
    shaderResourceViewDesc.Texture2D.MipLevels = 1;
 
    // 셰이더 리소스 뷰를 만듭니다.
    for(int i=0; i<BUFFER_COUNT; i++)
    {
        result = device->CreateShaderResourceView(m_renderTargetTextureArray[i], &shaderResourceViewDesc,
 &m_shaderResourceViewArray[i]);
        if(FAILED(result))
        {
            return false;
        }
    }
 
    // 깊이 버퍼의 구조체를 초기화합니다.
    D3D11_TEXTURE2D_DESC depthBufferDesc;
    ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
 
    // 깊이 버퍼의 구조체를 설정합니다.
    depthBufferDesc.Width = textureWidth;
    depthBufferDesc.Height = textureHeight;
    depthBufferDesc.MipLevels = 1;
    depthBufferDesc.ArraySize = 1;
    depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthBufferDesc.SampleDesc.Count = 1;
    depthBufferDesc.SampleDesc.Quality = 0;
    depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    depthBufferDesc.CPUAccessFlags = 0;
    depthBufferDesc.MiscFlags = 0;
 
    // 채워진 구조체를 사용하여 깊이 버퍼의 텍스처를 만듭니다.
    result = device->CreateTexture2D(&depthBufferDesc, NULL&m_depthStencilBuffer);
    if(FAILED(result))
    {
        return false;
    }
 
    // 깊이 스텐실 뷰 구조체를 초기화합니다.
    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
 
    // 깊이 스텐실 뷰 구조체를 설정합니다.
    depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    depthStencilViewDesc.Texture2D.MipSlice = 0;
 
    // 깊이 스텐실 뷰를 만듭니다.
    result = device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
    if(FAILED(result))
    {
        return false;
    }
 
    // 렌더링을 위해 뷰포트를 설정합니다.
    m_viewport.Width = (float)textureWidth;
    m_viewport.Height = (float)textureHeight;
    m_viewport.MinDepth = 0.0f;
    m_viewport.MaxDepth = 1.0f;
    m_viewport.TopLeftX = 0.0f;
    m_viewport.TopLeftY = 0.0f;
 
    return true;
}
 
 
void DeferredBuffersClass::Shutdown()
{
    if(m_depthStencilView)
    {
        m_depthStencilView->Release();
        m_depthStencilView = 0;
    }
 
    if(m_depthStencilBuffer)
    {
        m_depthStencilBuffer->Release();
        m_depthStencilBuffer = 0;
    }
 
    for(int i=0; i<BUFFER_COUNT; i++)
    {
        if(m_shaderResourceViewArray[i])
        {
            m_shaderResourceViewArray[i]->Release();
            m_shaderResourceViewArray[i] = 0;
        }
 
        if(m_renderTargetViewArray[i])
        {
            m_renderTargetViewArray[i]->Release();
            m_renderTargetViewArray[i] = 0;
        }
 
        if(m_renderTargetTextureArray[i])
        {
            m_renderTargetTextureArray[i]->Release();
            m_renderTargetTextureArray[i] = 0;
        }
    }
}
 
 
void DeferredBuffersClass::SetRenderTargets(ID3D11DeviceContext* deviceContext)
{
    // 렌더링 대상 뷰 배열 및 깊이 스텐실 버퍼를 출력 렌더 파이프 라인에 바인딩 합니다.
    deviceContext->OMSetRenderTargets(BUFFER_COUNT, m_renderTargetViewArray, m_depthStencilView);
    
    // 뷰포트를 설정합니다.
    deviceContext->RSSetViewports(1&m_viewport);
}
 
 
void DeferredBuffersClass::ClearRenderTargets(ID3D11DeviceContext* deviceContext, float red, float green, float blue,
 float alpha)
{
    // 버퍼를 지울 색을 설정합니다.
    float color[4= { red, green, blue, alpha };
 
    // 렌더 타겟 버퍼를 지웁니다.
    for(int i=0; i<BUFFER_COUNT; i++)
    {
        deviceContext->ClearRenderTargetView(m_renderTargetViewArray[i], color);
    }
 
    // 깊이 버퍼를 지웁니다.
    deviceContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
 
 
ID3D11ShaderResourceView* DeferredBuffersClass::GetShaderResourceView(int view)
{
    return m_shaderResourceViewArray[view];
}
cs



이것들은 지연된 HLSL 쉐이더입니다. 우리는 이것을 사용하여 씬 데이터를 텍스처 버퍼로 렌더링합니다. 지연 버텍스 쉐이더의 경우 이전 튜토리얼에서와 똑같은 작업을 수행합니다. 모든 변경 사항은 실제로 픽셀 쉐이더에 있습니다.


Deferred_vs.hlsl


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
////////////////////////////////////////////////////////////////////////////////
// Filename: deferred_vs.hlsl
////////////////////////////////////////////////////////////////////////////////
 
 
//////////////////////
// CONSTANT BUFFERS //
//////////////////////
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};
 
 
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType DeferredVertexShader(VertexInputType input)
{
    PixelInputType output;
    
    
    // 적절한 행렬 계산을 위해 위치 벡터를 4 단위로 변경합니다.
    input.position.w = 1.0f;
 
    // 월드, 뷰 및 투영 행렬에 대한 정점의 위치를 ​​계산합니다.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);
    
    // 픽셀 쉐이더의 텍스처 좌표를 저장한다.
    output.tex = input.tex;
    
    // 월드 행렬에 대해서만 법선 벡터를 계산합니다.
    output.normal = mul(input.normal, (float3x3)worldMatrix);
    
    // 법선 벡터를 정규화합니다.
    output.normal = normalize(output.normal);
 
    return output;
}
cs



Deferred_ps.hlsl


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
////////////////////////////////////////////////////////////////////////////////
// Filename: deferred_ps.hlsl
////////////////////////////////////////////////////////////////////////////////
 
 
//////////////
// TEXTURES //
//////////////
Texture2D shaderTexture : register(t0);
 
 
///////////////////
// SAMPLE STATES //
///////////////////
SamplerState SampleTypeWrap : register(s0);
 
 
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};
 
struct PixelOutputType
{
    float4 color : SV_Target0;
    float4 normal : SV_Target1;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
PixelOutputType DeferredPixelShader(PixelInputType input) : SV_TARGET
{
    PixelOutputType output;
 
 
    // 텍스처에서 색상을 샘플링하고 렌더링 대상에 출력하기 위해 저장합니다.
    output.color = shaderTexture.Sample(SampleTypeWrap, input.tex);
    
    // 렌더 타겟에 아웃풋을 저장한다.
    output.normal = float4(input.normal, 1.0f);
 
    return output;
}
cs



지연 쉐이더의 기능을 캡슐화하는 클래스입니다. 일반 쉐이더와 크게 다르지 않습니다.


Deferredshaderclass.h


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#pragma once
 
class DeferredShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
public:
    DeferredShaderClass();
    DeferredShaderClass(const DeferredShaderClass&);
    ~DeferredShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool Render(ID3D11DeviceContext*int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*);
 
private:
    bool InitializeShader(ID3D11Device*, HWND, const WCHAR*const WCHAR*);
    void ShutdownShader();
    void OutputShaderErrorMessage(ID3D10Blob*, HWND, const WCHAR*);
 
    bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*);
    void RenderShader(ID3D11DeviceContext*int);
 
private:
    ID3D11VertexShader* m_vertexShader = nullptr;
    ID3D11PixelShader* m_pixelShader = nullptr;
    ID3D11InputLayout* m_layout = nullptr;
    ID3D11Buffer* m_matrixBuffer = nullptr;
    ID3D11SamplerState* m_sampleStateWrap = nullptr;
};
cs



Deferredshaderclass.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#include "stdafx.h"
#include "DeferredShaderClass.h"
 
 
DeferredShaderClass::DeferredShaderClass()
{
}
 
 
DeferredShaderClass::DeferredShaderClass(const DeferredShaderClass& other)
{
}
 
 
DeferredShaderClass::~DeferredShaderClass()
{
}
 
 
bool DeferredShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더를 초기화합니다.
    return InitializeShader(device, hwnd, L"../Dx11Demo_50/deferred_vs.hlsl", L"../Dx11Demo_50/deferred_ps.hlsl");
}
 
 
void DeferredShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련된 객체를 종료합니다.
    ShutdownShader();
}
 
 
bool DeferredShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix,
 XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
{
    // 렌더링에 사용할 셰이더 매개 변수를 설정합니다.
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture))
    {
        return false;
    }
 
    // 설정된 버퍼를 셰이더로 렌더링한다.
    RenderShader(deviceContext, indexCount);
 
    return true;
}
 
 
bool DeferredShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage = nullptr;
    
    // 버텍스 쉐이더 코드를 컴파일한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    result = D3DCompileFromFile(vsFilename, NULLNULL"DeferredVertexShader""vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
    &vertexShaderBuffer, &errorMessage);
    if (FAILED(result))
    {
        // 셰이더 컴파일 실패시 오류메시지를 출력합니다.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
        }
        // 컴파일 오류가 아니라면 셰이더 파일을 찾을 수 없는 경우입니다.
        else
        {
            MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
        }
    
        return false;
    }
    
    // 픽셀 쉐이더 코드를 컴파일한다.
    ID3D10Blob* pixelShaderBuffer = nullptr;
    result = D3DCompileFromFile(psFilename, NULLNULL"DeferredPixelShader""ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
 &pixelShaderBuffer, &errorMessage);
    if (FAILED(result))
    {
        // 셰이더 컴파일 실패시 오류메시지를 출력합니다.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
        }
        // 컴파일 오류가 아니라면 셰이더 파일을 찾을 수 없는 경우입니다.
        else
        {
            MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK);
        }
    
        return false;
    }
    
    // 버퍼로부터 정점 셰이더를 생성한다.
    result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL,
 &m_vertexShader);
    if (FAILED(result))
    {
        return false;
    }
    
    // 버퍼에서 픽셀 쉐이더를 생성합니다.
    result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL,
 &m_pixelShader);
    if (FAILED(result))
    {
        return false;
    }
    
    // 정점 입력 레이아웃 구조체를 설정합니다.
    // 이 설정은 ModelClass와 셰이더의 VertexType 구조와 일치해야합니다.
    D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
    polygonLayout[0].SemanticName = "POSITION";
    polygonLayout[0].SemanticIndex = 0;
    polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[0].InputSlot = 0;
    polygonLayout[0].AlignedByteOffset = 0;
    polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[0].InstanceDataStepRate = 0;
    
    polygonLayout[1].SemanticName = "TEXCOORD";
    polygonLayout[1].SemanticIndex = 0;
    polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
    polygonLayout[1].InputSlot = 0;
    polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[1].InstanceDataStepRate = 0;
    
    polygonLayout[2].SemanticName = "NORMAL";
    polygonLayout[2].SemanticIndex = 0;
    polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[2].InputSlot = 0;
    polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[2].InstanceDataStepRate = 0;
    
    // 레이아웃의 요소 수를 가져옵니다.
    unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
    
    // 정점 입력 레이아웃을 만듭니다.
    result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(),
        vertexShaderBuffer->GetBufferSize(), &m_layout);
    if (FAILED(result))
    {
        return false;
    }
    
    // 더 이상 사용되지 않는 정점 셰이더 퍼버와 픽셀 셰이더 버퍼를 해제합니다.
    vertexShaderBuffer->Release();
    vertexShaderBuffer = 0;
    
    pixelShaderBuffer->Release();
    pixelShaderBuffer = 0;
    
    // 랩 텍스처 샘플러 상태 구조체를 설정합니다.
    D3D11_SAMPLER_DESC samplerDesc;
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 1;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samplerDesc.BorderColor[0= 0;
    samplerDesc.BorderColor[1= 0;
    samplerDesc.BorderColor[2= 0;
    samplerDesc.BorderColor[3= 0;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
    
    //텍스처 샘플러 상태를 만듭니다.
    result = device->CreateSamplerState(&samplerDesc, &m_sampleStateWrap);
    if(FAILED(result))
    {
        return false;
    }
    
    // 버텍스 쉐이더에있는 동적 행렬 상수 버퍼의 구조체를 설정합니다.
    D3D11_BUFFER_DESC matrixBufferDesc;
    matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
    matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    matrixBufferDesc.MiscFlags = 0;
    matrixBufferDesc.StructureByteStride = 0;
    
    // 이 클래스 내에서 정점 셰이더 상수 버퍼에 액세스 할 수 있도록 상수 버퍼 포인터를 만듭니다.
    result = device->CreateBuffer(&matrixBufferDesc, NULL&m_matrixBuffer);
    if(FAILED(result))
    {
        return false;
    }    
    
    return true;
}
 
 
void DeferredShaderClass::ShutdownShader()
{
    // 행렬 상수 버퍼를 해제합니다.
    if (m_matrixBuffer)
    {
        m_matrixBuffer->Release();
        m_matrixBuffer = 0;
    }
 
    // 샘플러 상태를 해제한다.
    if (m_sampleStateWrap)
    {
        m_sampleStateWrap->Release();
        m_sampleStateWrap = 0;
    }
    // 레이아웃을 해제합니다.
    if (m_layout)
    {
        m_layout->Release();
        m_layout = 0;
    }
 
    // 픽셀 쉐이더를 해제합니다.
    if (m_pixelShader)
    {
        m_pixelShader->Release();
        m_pixelShader = 0;
    }
 
    // 버텍스 쉐이더를 해제합니다.
    if (m_vertexShader)
    {
        m_vertexShader->Release();
        m_vertexShader = 0;
    }
}
 
 
void DeferredShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, const WCHAR* shaderFilename)
{
    // 에러 메시지를 출력창에 표시합니다.
    OutputDebugStringA(reinterpret_cast<const char*>(errorMessage->GetBufferPointer()));
 
    // 에러 메세지를 반환합니다.
    errorMessage->Release();
    errorMessage = 0;
 
    // 컴파일 에러가 있음을 팝업 메세지로 알려줍니다.
    MessageBox(hwnd, L"Error compiling shader.", shaderFilename, MB_OK);
}
 
bool DeferredShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
    XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
{
// 행렬을 transpose하여 셰이더에서 사용할 수 있게 합니다
    worldMatrix = XMMatrixTranspose(worldMatrix);
    viewMatrix = XMMatrixTranspose(viewMatrix);
    projectionMatrix = XMMatrixTranspose(projectionMatrix);
 
    // 상수 버퍼의 내용을 쓸 수 있도록 잠급니다.
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    if (FAILED(deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
    MatrixBufferType* dataPtr = (MatrixBufferType*)mappedResource.pData;
 
    // 상수 버퍼에 행렬을 복사합니다.
    dataPtr->world = worldMatrix;
    dataPtr->view = viewMatrix;
    dataPtr->projection = projectionMatrix;
 
    // 상수 버퍼의 잠금을 풉니다.
    deviceContext->Unmap(m_matrixBuffer, 0);
 
    // 정점 셰이더에서의 상수 버퍼의 위치를 설정합니다.
    unsigned int bufferNumber = 0;
 
    // 마지막으로 정점 셰이더의 상수 버퍼를 바뀐 값으로 바꿉니다.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1&m_matrixBuffer);
 
    // 픽셀 셰이더에서 셰이더 텍스처 리소스를 설정합니다.
    deviceContext->PSSetShaderResources(01&texture);
 
    return true;
}
 
 
void DeferredShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
    // 정점 입력 레이아웃을 설정합니다.
    deviceContext->IASetInputLayout(m_layout);
 
    // 삼각형을 그릴 정점 셰이더와 픽셀 셰이더를 설정합니다.
    deviceContext->VSSetShader(m_vertexShader, NULL0);
    deviceContext->PSSetShader(m_pixelShader, NULL0);
 
    // 픽셀 쉐이더에서 샘플러 상태를 설정합니다.
    deviceContext->PSSetSamplers(01&m_sampleStateWrap);
 
    // 삼각형을 그립니다.
    deviceContext->DrawIndexed(indexCount, 00);
}
cs



지연 렌더링을 처리하기 위해 다시 작성된 지향성 라이트 셰이더입니다.


Light_vs.hlsl


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
////////////////////////////////////////////////////////////////////////////////
// Filename: light_vs.hlsl
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};
 
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
};
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType LightVertexShader(VertexInputType input)
{
    PixelInputType output = (PixelInputType)0;
    
 
    // 적절한 행렬 계산을 위해 위치 벡터를 4 단위로 변경합니다.
    input.position.w = 1.0f;
 
    // 월드, 뷰 및 투영 행렬에 대한 정점의 위치를 ​​계산합니다.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);
    
    // 픽셀 쉐이더의 텍스처 좌표를 저장한다.
    output.tex = input.tex;
    
    return output;
}
cs



Light_ps.hlsl


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
////////////////////////////////////////////////////////////////////////////////
// Filename: light_ps.hlsl
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
Texture2D colorTexture : register(t0);
Texture2D normalTexture : register(t1);
 
 
///////////////////
// SAMPLE STATES //
///////////////////
SamplerState SampleTypePoint : register(s0);
 
 
//////////////////////
// CONSTANT BUFFERS //
//////////////////////
cbuffer LightBuffer
{
    float3 lightDirection;
    float padding;
};
 
 
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
    float4 colors;
    float4 normals;
    float3 lightDir;
    float lightIntensity;
    float4 outputColor;
 
 
    // 이 텍스처 좌표 위치에서 포인트 샘플러를 사용하여 컬러 렌더링 텍스처에서 색상을 샘플링합니다.
    colors = colorTexture.Sample(SampleTypePoint, input.tex);
 
    // 이 텍스쳐 좌표 위치에있는 포인트 샘플러를 사용하여 normal 렌더 텍스처로부터 법선을 샘플링합니다.
    normals = normalTexture.Sample(SampleTypePoint, input.tex);
    
    // 계산을 위해 빛 방향을 반전시킵니다.
    lightDir = -lightDirection;
 
    // 이 픽셀의 빛의 양을 계산합니다.
    lightIntensity = saturate(dot(normals.xyz, lightDir));
 
    // 광도와 결합 된 픽셀의 색상을 기반으로 최종 색상 확산 량을 결정합니다.
    outputColor = saturate(colors * lightIntensity);
 
    return outputColor;
}
cs





LightShaderClass가 지연 쉐이딩을 처리하도록 다시 작성되었습니다.


Lightshaderclass.h


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#pragma once
 
class LightShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    struct LightBufferType
    {
        XMFLOAT3 lightDirection;
        float padding;
    };
public:
    LightShaderClass();
    LightShaderClass(const LightShaderClass&);
    ~LightShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool Render(ID3D11DeviceContext*int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*,
 ID3D11ShaderResourceView*, XMFLOAT3);
    
private:
    bool InitializeShader(ID3D11Device*, HWND, const WCHAR*const WCHAR*);
    void ShutdownShader();
    void OutputShaderErrorMessage(ID3D10Blob*, HWND, const WCHAR*);
 
    bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*,
 ID3D11ShaderResourceView*, XMFLOAT3);
    void RenderShader(ID3D11DeviceContext*int);
 
private:
    ID3D11VertexShader* m_vertexShader = nullptr;
    ID3D11PixelShader* m_pixelShader = nullptr;
    ID3D11InputLayout* m_layout = nullptr;
    ID3D11SamplerState* m_sampleState = nullptr;
    ID3D11Buffer* m_matrixBuffer = nullptr;
    ID3D11Buffer* m_lightBuffer = nullptr;
};
cs



Lightshaderclass.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#include "stdafx.h"
#include "LightShaderClass.h"
 
 
LightShaderClass::LightShaderClass()
{
}
 
 
LightShaderClass::LightShaderClass(const LightShaderClass& other)
{
}
 
 
LightShaderClass::~LightShaderClass()
{
}
 
 
bool LightShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더를 초기화합니다.
    return InitializeShader(device, hwnd, L"../Dx11Demo_50/light_vs.hlsl", L"../Dx11Demo_50/light_ps.hlsl");
}
 
 
void LightShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련된 객체를 종료합니다.
    ShutdownShader();
}
 
 
bool LightShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, 
    XMMATRIX projectionMatrix, ID3D11ShaderResourceView* colorTexture, ID3D11ShaderResourceView* normalTexture,
 XMFLOAT3 lightDirection)
{
    // 렌더링에 사용할 셰이더 매개 변수를 설정합니다.
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, colorTexture, normalTexture,
  lightDirection))
    {
        return false;
    }
 
    // 설정된 버퍼를 셰이더로 렌더링한다.
    RenderShader(deviceContext, indexCount);
 
    return true;
}
 
 
bool LightShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    result = D3DCompileFromFile(vsFilename, NULLNULL"LightVertexShader""vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
    &vertexShaderBuffer, &errorMessage);
    if (FAILED(result))
    {
        // 셰이더 컴파일 실패시 오류메시지를 출력합니다.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
        }
        // 컴파일 오류가 아니라면 셰이더 파일을 찾을 수 없는 경우입니다.
        else
        {
            MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
        }
 
        return false;
    }
 
    // 픽셀 쉐이더 코드를 컴파일한다.
    ID3D10Blob* pixelShaderBuffer = nullptr;
    result = D3DCompileFromFile(psFilename, NULLNULL"LightPixelShader""ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
 &pixelShaderBuffer, &errorMessage);
    if (FAILED(result))
    {
        // 셰이더 컴파일 실패시 오류메시지를 출력합니다.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
        }
        // 컴파일 오류가 아니라면 셰이더 파일을 찾을 수 없는 경우입니다.
        else
        {
            MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK);
        }
 
        return false;
    }
 
    // 버퍼로부터 정점 셰이더를 생성한다.
    result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL,
 &m_vertexShader);
    if (FAILED(result))
    {
        return false;
    }
 
    // 버퍼에서 픽셀 쉐이더를 생성합니다.
    result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL,
 &m_pixelShader);
    if (FAILED(result))
    {
        return false;
    }
 
    // 정점 입력 레이아웃 구조체를 설정합니다.
    // 이 설정은 ModelClass와 셰이더의 VertexType 구조와 일치해야합니다.
    D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
    polygonLayout[0].SemanticName = "POSITION";
    polygonLayout[0].SemanticIndex = 0;
    polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[0].InputSlot = 0;
    polygonLayout[0].AlignedByteOffset = 0;
    polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[0].InstanceDataStepRate = 0;
 
    polygonLayout[1].SemanticName = "TEXCOORD";
    polygonLayout[1].SemanticIndex = 0;
    polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
    polygonLayout[1].InputSlot = 0;
    polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[1].InstanceDataStepRate = 0;
 
    // 레이아웃의 요소 수를 가져옵니다.
    UINT numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
 
    // 정점 입력 레이아웃을 만듭니다.
    result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(),
        vertexShaderBuffer->GetBufferSize(), &m_layout);
    if (FAILED(result))
    {
        return false;
    }
 
    // 더 이상 사용되지 않는 정점 셰이더 퍼버와 픽셀 셰이더 버퍼를 해제합니다.
    vertexShaderBuffer->Release();
    vertexShaderBuffer = 0;
 
    pixelShaderBuffer->Release();
    pixelShaderBuffer = 0;
 
    // 텍스처 샘플러 상태 구조체를 생성 및 설정합니다.
    D3D11_SAMPLER_DESC samplerDesc;
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 1;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samplerDesc.BorderColor[0= 0;
    samplerDesc.BorderColor[1= 0;
    samplerDesc.BorderColor[2= 0;
    samplerDesc.BorderColor[3= 0;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
 
    // 텍스처 샘플러 상태를 만듭니다.
    result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
    if (FAILED(result))
    {
        return false;
    }
 
    // 정점 셰이더에 있는 행렬 상수 버퍼의 구조체를 작성합니다.
    D3D11_BUFFER_DESC matrixBufferDesc;
    matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
    matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    matrixBufferDesc.MiscFlags = 0;
    matrixBufferDesc.StructureByteStride = 0;
 
    // 상수 버퍼 포인터를 만들어 이 클래스에서 정점 셰이더 상수 버퍼에 접근할 수 있게 합니다.
    result = device->CreateBuffer(&matrixBufferDesc, NULL&m_matrixBuffer);
    if (FAILED(result))
    {
        return false;
    }
 
    // 픽셀 쉐이더에있는 광원 동적 상수 버퍼의 구조체를 설정합니다.
    // D3D11_BIND_CONSTANT_BUFFER를 사용하면 ByteWidth가 항상 16의 배수 여야하며 그렇지 않으면 CreateBuffer가 실패합니다.
    D3D11_BUFFER_DESC lightBufferDesc;
    lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    lightBufferDesc.ByteWidth = sizeof(LightBufferType);
    lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    lightBufferDesc.MiscFlags = 0;
    lightBufferDesc.StructureByteStride = 0;
 
    // 이 클래스 내에서 정점 셰이더 상수 버퍼에 액세스 할 수 있도록 상수 버퍼 포인터를 만듭니다.
    result = device->CreateBuffer(&lightBufferDesc, NULL&m_lightBuffer);
    if(FAILED(result))
    {
        return false;
    }    
 
    return true;
}
 
 
void LightShaderClass::ShutdownShader()
{
    // 광원 상수 버퍼를 해제합니다.
    if(m_lightBuffer)
    {
        m_lightBuffer->Release();
        m_lightBuffer = 0;
    }
 
    // 행렬 상수 버퍼를 해제합니다.
    if (m_matrixBuffer)
    {
        m_matrixBuffer->Release();
        m_matrixBuffer = 0;
    }
 
    // 샘플러 상태를 해제한다.
    if (m_sampleState)
    {
        m_sampleState->Release();
        m_sampleState = 0;
    }
 
    // 레이아웃을 해제합니다.
    if (m_layout)
    {
        m_layout->Release();
        m_layout = 0;
    }
 
    // 픽셀 쉐이더를 해제합니다.
    if (m_pixelShader)
    {
        m_pixelShader->Release();
        m_pixelShader = 0;
    }
 
    // 버텍스 쉐이더를 해제합니다.
    if (m_vertexShader)
    {
        m_vertexShader->Release();
        m_vertexShader = 0;
    }
}
 
 
void LightShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, const WCHAR* shaderFilename)
{
    // 에러 메시지를 출력창에 표시합니다.
    OutputDebugStringA(reinterpret_cast<const char*>(errorMessage->GetBufferPointer()));
 
    // 에러 메세지를 반환합니다.
    errorMessage->Release();
    errorMessage = 0;
 
    // 컴파일 에러가 있음을 팝업 메세지로 알려줍니다.
    MessageBox(hwnd, L"Error compiling shader.", shaderFilename, MB_OK);
}
 
bool LightShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
    XMMATRIX projectionMatrix, ID3D11ShaderResourceView* colorTexture, ID3D11ShaderResourceView* normalTexture,
    XMFLOAT3 lightDirection)
{
// 행렬을 transpose하여 셰이더에서 사용할 수 있게 합니다
    worldMatrix = XMMatrixTranspose(worldMatrix);
    viewMatrix = XMMatrixTranspose(viewMatrix);
    projectionMatrix = XMMatrixTranspose(projectionMatrix);
 
    // 상수 버퍼의 내용을 쓸 수 있도록 잠급니다.
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    if (FAILED(deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
    MatrixBufferType* dataPtr = (MatrixBufferType*)mappedResource.pData;
 
    // 상수 버퍼에 행렬을 복사합니다.
    dataPtr->world = worldMatrix;
    dataPtr->view = viewMatrix;
    dataPtr->projection = projectionMatrix;
 
    // 상수 버퍼의 잠금을 풉니다.
    deviceContext->Unmap(m_matrixBuffer, 0);
 
    // 정점 셰이더에서의 상수 버퍼의 위치를 설정합니다.
    unsigned int bufferNumber = 0;
 
    // 마지막으로 정점 셰이더의 상수 버퍼를 바뀐 값으로 바꿉니다.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1&m_matrixBuffer);
 
    // Set shader texture resource in the pixel shader.
    deviceContext->PSSetShaderResources(01&colorTexture);
    deviceContext->PSSetShaderResources(11&normalTexture);
    
    // light constant buffer를 잠글 수 있도록 기록한다.
    if(FAILED(deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
    LightBufferType* dataPtr2 = (LightBufferType*)mappedResource.pData;
 
    // 조명 변수를 상수 버퍼에 복사합니다.
    dataPtr2->lightDirection = lightDirection;
    dataPtr2->padding = 0.0f;
 
    // 상수 버퍼의 잠금을 해제합니다.
    deviceContext->Unmap(m_lightBuffer, 0);
 
    // 픽셀 쉐이더에서 광원 상수 버퍼의 위치를 ??설정합니다.
    bufferNumber = 0;
 
    // 마지막으로 업데이트 된 값으로 픽셀 쉐이더에서 광원 상수 버퍼를 설정합니다.
    deviceContext->PSSetConstantBuffers(bufferNumber, 1&m_lightBuffer);
    return true;
}
 
 
void LightShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
    // 정점 입력 레이아웃을 설정합니다.
    deviceContext->IASetInputLayout(m_layout);
 
    // 삼각형을 그릴 정점 셰이더와 픽셀 셰이더를 설정합니다.
    deviceContext->VSSetShader(m_vertexShader, NULL0);
    deviceContext->PSSetShader(m_pixelShader, NULL0);
 
    // 픽셀 쉐이더에서 샘플러 상태를 설정합니다.
    deviceContext->PSSetSamplers(01&m_sampleState);
 
    // 삼각형을 그립니다.
    deviceContext->DrawIndexed(indexCount, 00);
}
cs



Applicationclass.h


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#pragma once
 
/////////////
// GLOBALS //
/////////////
const bool FULL_SCREEN = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
 
 
class InputClass;
class D3DClass;
class CameraClass;
class LightClass;
class ModelClass;
class OrthoWindowClass;
class DeferredBuffersClass;
class DeferredShaderClass;
class LightShaderClass;
 
 
class ApplicationClass
{
public:
    ApplicationClass();
    ApplicationClass(const ApplicationClass&);
    ~ApplicationClass();
 
    bool Initialize(HINSTANCE, HWND, intint);
    void Shutdown();
    bool Frame();
 
private:
    bool Render();
    bool RenderSceneToTexture();
 
private:
    InputClass* m_Input = nullptr;
    D3DClass* m_D3D = nullptr;
    CameraClass* m_Camera = nullptr;
    LightClass* m_Light = nullptr;
    ModelClass* m_Model = nullptr;
    OrthoWindowClass* m_FullScreenWindow = nullptr;
    DeferredBuffersClass* m_DeferredBuffers = nullptr;
    DeferredShaderClass* m_DeferredShader = nullptr;
    LightShaderClass* m_LightShader = nullptr;
};
cs



Applicationclass.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#include "stdafx.h"
#include "inputclass.h"
#include "d3dclass.h"
#include "cameraclass.h"
#include "lightclass.h"
#include "modelclass.h"
#include "orthowindowclass.h"
#include "deferredbuffersclass.h"
#include "deferredshaderclass.h"
#include "lightshaderclass.h"
#include "ApplicationClass.h"
 
 
ApplicationClass::ApplicationClass()
{
}
 
 
ApplicationClass::ApplicationClass(const ApplicationClass& other)
{
}
 
 
ApplicationClass::~ApplicationClass()
{
}
 
 
bool ApplicationClass::Initialize(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight)
{
    // 입력 개체를 만듭니다. 입력 객체는 사용자로부터 키보드 및 마우스 입력 읽기를 처리하는 데 사용됩니다.
    m_Input = new InputClass;
    if(!m_Input)
    {
        return false;
    }
 
    // 입력 개체를 초기화 합니다.
    bool result = m_Input->Initialize(hinstance, hwnd, screenWidth, screenHeight);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the input object.", L"Error", MB_OK);
        return false;
    }
 
    // Direct3D 객체를 생성합니다.
    m_D3D = new D3DClass;
    if(!m_D3D)
    {
        return false;
    }
 
    // Direct3D 객체를 초기화 합니다.
    result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize DirectX 11.", L"Error", MB_OK);
        return false;
    }
 
    // 카메라 객체를 생성합니다.
    m_Camera = new CameraClass;
    if(!m_Camera)
    {
        return false;
    }
 
    // 카메라의 초기 위치를 설정하고 렌더링에 필요한 행렬을 만듭니다.
    m_Camera->SetPosition(XMFLOAT3(0.0f, 0.0f, -5.0f));
    m_Camera->Render();
    m_Camera->RenderBaseViewMatrix();
 
    // 조명 객체를 생성합니다.
    m_Light = new LightClass;
    if(!m_Light)
    {
        return false;
    }
 
    // 조명 객체를 초기화 합니다.
    m_Light->SetDiffuseColor(XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f));
    m_Light->SetDirection(XMFLOAT3(0.0f, 0.0f, 1.0f));
    
    // 모델 객체를 생성합니다.
    m_Model = new ModelClass;
    if(!m_Model)
    {
        return false;
    }
 
    // 모델 객체를 초기화 합니다.
    result = m_Model->Initialize(m_D3D->GetDevice(), "../Dx11Demo_50/data/cube.txt", L"../Dx11Demo_50/data/seafloor.dds");
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
        return false;
    }
 
    // 전체 화면 ortho window 객체를 생성합니다.
    m_FullScreenWindow = new OrthoWindowClass;
    if(!m_FullScreenWindow)
    {
        return false;
    }
 
    // 전체 화면 ortho window 객체를 초기화 합니다.
    result = m_FullScreenWindow->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the full screen ortho window object.", L"Error", MB_OK);
        return false;
    }
 
    // 지연된 버퍼 객체를 생성합니다.
    m_DeferredBuffers = new DeferredBuffersClass;
    if(!m_DeferredBuffers)
    {
        return false;
    }
 
    // 지연된 버퍼 객체를 초기화 합니다.
    result = m_DeferredBuffers->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, SCREEN_DEPTH, SCREEN_NEAR);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the deferred buffers object.", L"Error", MB_OK);
        return false;
    }
 
    // 지연된 셰이더 객체를 생성합니다.
    m_DeferredShader = new DeferredShaderClass;
    if(!m_DeferredShader)
    {
        return false;
    }
 
    // 지연된 셰이더 객체를 초기화 합니다.
    result = m_DeferredShader->Initialize(m_D3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the deferred shader object.", L"Error", MB_OK);
        return false;
    }
 
    // 조명 쉐이더 객체를 생성합니다.
    m_LightShader = new LightShaderClass;
    if(!m_LightShader)
    {
        return false;
    }
 
    // 조명 쉐이더 객체를 초기화 합니다.
    result = m_LightShader->Initialize(m_D3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
        return false;
    }
 
    return true;
}
 
 
void ApplicationClass::Shutdown()
{
    // 조명 쉐이더 객체를 해제합니다.
    if(m_LightShader)
    {
        m_LightShader->Shutdown();
        delete m_LightShader;
        m_LightShader = 0;
    }
 
    // 지연된 쉐이더 객체를 해제합니다.
    if(m_DeferredShader)
    {
        m_DeferredShader->Shutdown();
        delete m_DeferredShader;
        m_DeferredShader = 0;
    }
 
    // 지연된 버퍼 객체를 해제합니다.
    if(m_DeferredBuffers)
    {
        m_DeferredBuffers->Shutdown();
        delete m_DeferredBuffers;
        m_DeferredBuffers = 0;
    }
 
    // 전체 화면 ortho window 객체를 해제합니다.
    if(m_FullScreenWindow)
    {
        m_FullScreenWindow->Shutdown();
        delete m_FullScreenWindow;
        m_FullScreenWindow = 0;
    }
 
    // 모델 객체를 해제합니다.
    if(m_Model)
    {
        m_Model->Shutdown();
        delete m_Model;
        m_Model = 0;
    }
 
    // 조명 객체를 해제합니다.
    if(m_Light)
    {
        delete m_Light;
        m_Light = 0;
    }
 
    // 카메라 객체를 해제합니다.
    if(m_Camera)
    {
        delete m_Camera;
        m_Camera = 0;
    }
    
    // D3D 객체를 해제합니다.
    if(m_D3D)
    {
        m_D3D->Shutdown();
        delete m_D3D;
        m_D3D = 0;
    }
 
    // 입력 개체를 해제합니다.
    if(m_Input)
    {
        m_Input->Shutdown();
        delete m_Input;
        m_Input = 0;
    }
}
 
 
bool ApplicationClass::Frame()
{
    // 사용자 입력을 읽습니다.
    if(!m_Input->Frame())
    {
        return false;
    }
    
    // 사용자가 ESC 키를 누르고 응용 프로그램을 종료할 것인지 확인합니다.
    if(m_Input->IsEscapePressed() == true)
    {
        return false;
    }
 
    // 그래픽을 렌더링 합니다.
    return Render();
}
 
 
bool ApplicationClass::Render()
{
    XMMATRIX worldMatrix, baseViewMatrix, orthoMatrix;
 
    // 먼저 장면을 텍스처로 렌더링합니다.
    if(!RenderSceneToTexture())
    {
        return false;
    }
 
    // 장면을 시작할 버퍼를 지운다.
    m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져옵니다.
    m_D3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetBaseViewMatrix(baseViewMatrix);
    m_D3D->GetOrthoMatrix(orthoMatrix);
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_D3D->TurnZBufferOff();
 
    // 그래픽 파이프 라인에 전체 화면 직교 윈도우 버텍스와 인덱스 버퍼를 배치하여 그리기를 준비합니다.
    m_FullScreenWindow->Render(m_D3D->GetDeviceContext());
 
    // 지연 조명 쉐이더와 렌더링 버퍼를 사용하여 전체 화면 정사영 윈도우를 렌더링합니다.
    m_LightShader->Render(m_D3D->GetDeviceContext(), m_FullScreenWindow->GetIndexCount(), worldMatrix, baseViewMatrix,
orthoMatrix, m_DeferredBuffers->GetShaderResourceView(0), m_DeferredBuffers->GetShaderResourceView(1), 
               m_Light->GetDirection());
 
    // 모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켭니다.
    m_D3D->TurnZBufferOn();
    
    // 렌더링 된 장면을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
 
 
bool ApplicationClass::RenderSceneToTexture()
{
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
 
    // 렌더링 대상을 텍스처에 렌더링으로 설정합니다.
    m_DeferredBuffers->SetRenderTargets(m_D3D->GetDeviceContext());
 
    // 렌더링에 텍스처를 지웁니다.
    m_DeferredBuffers->ClearRenderTargets(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f);
 
    // d3d 객체에서 월드 행렬을 가져옵니다.
    m_D3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetProjectionMatrix(projectionMatrix);
 
    // 각 프레임의 rotation 변수를 업데이트합니다.
    static float rotation = 0.0f;
    rotation += (float)XM_PI * 0.007f;
    if(rotation > 360.0f)
    {
        rotation -= 360.0f;
    }
 
    // 회전값으로 월드 행렬을 회전하여 큐브가 회전하도록 합니다.
    worldMatrix = XMMatrixRotationY(rotation);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비합니다.
    m_Model->Render(m_D3D->GetDeviceContext());
 
    // 지연된 셰이더를 사용하여 모델을 렌더링합니다.
    m_DeferredShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix,
 m_Model->GetTexture());
 
    // 렌더 버퍼가 아닌 원래의 백 버퍼로 렌더링 타겟을 다시 설정합니다.
    m_D3D->SetBackBufferRenderTarget();
 
    // 뷰포트를 원본으로 다시 설정합니다.
    m_D3D->ResetViewport();
 
    return true;
}
cs



출력 화면




마치면서


이제는 지연된 음영을 사용하여 렌더링 할 수 있습니다.



연습문제


1. 포인트 라이트 지연 셰이더를 만듭니다.


2. 수백 개의 점등을 장면에 추가하십시오.


3. 데이터 압축 및 축소 / 축소 렌더링 텍스처를 사용하십시오.


4. 다른 셰이더의 일부를 변환하여 일반 매핑 및 그림자와 같은 지연된 음영을 사용합니다.



소스코드


소스코드 : Dx11Demo_50.zip