Thinking Different





Tutorial 5 - 텍스쳐



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




이 튜토리얼은 DirectX 11에서 텍스처를 사용하는 방법을 설명합니다. 텍스처를 사용하면 도형 표면에 사진과 다른 이미지를 적용하여 더욱 현실적인 장면을 연출할 수 있습니다. 이번 듀토리얼에서는 아래와 같은 사진을 이용하여 작성해보도록 하겠습니다.



이 이미지를 지난 듀토리얼(삼각형 만들기)에 덮어 씌어주면 아래와 같은 이미지로 도형 표면이 변하게 됩니다.



우리가 사용할 이미지의 형식은 .tga 파일입니다. 이것은 빨강, 녹색, 파랑 및 알파 채널을 지원하는 일반적인 그래픽 형식입니다. 일반적으로 모든 이미지 편집 소프트웨어를 사용하여 targa 파일을 만들고 편집 할 수 있습니다. 그리고 파일 형식은 대부분 간단합니다.


그리고 코드에 들어가기 전에 텍스처 매핑이 어떻게 작동하는지 구조를 확인해야 합니다. .tga 이미지의 픽셀을 도형에 매핑하기 위해 텍셀 좌표계(Texel Coordinate System)를 사용합니다. 이 시스템은 픽셀의 정수 값을 0.0f에서 1.0f 사이의 부동 소수점 값으로 변환합니다. 예를 들어, 텍스처 폭이 256 픽셀의 경우, 최초의 픽셀은 0.0f, 256 번째의 픽셀은 1.0f, 128의 중간 픽셀은 0.5f에 매핑됩니다.



텍셀 좌표계의 이해


텍셀 좌표계의 이해를 돕기위해 아래 그림을 통해 설명을 진행하도록 하겠습니다.




텍셀 좌표계에서 너비(가로) 값의 이름은 "U"이고 높이(세로) 값의 이름은 "V"입니다. 너비는 왼쪽에서 0.0에서 오른쪽으로 1.0 이 됩니다. 높이는 맨 위의 0.0에서 맨 아래의 1.0까지 아래쪽으로 높아집니다. 예를 들어 왼쪽 상단은 U 0.0, V 0.0으로 표시되고 오른쪽 하단은 U 1.0, V 1.0으로 표시됩니다.




이제 텍스쳐가 어떻게 씌워지는지 알았으므로 이번 튜토리얼에서 업데이트된 프레임워크를 살펴보도록 하겠습니다.




프레임워크 업데이트




지난 튜토리얼에서 달라진 점은 ModelClass 안에 TextureClass라는 클래스가 들어왔고, ColorShaderClass를 TextureShaderClass라는 클래스가 대체했다는 것입니다. 우선 새로운 HLSL 텍스쳐 셰이더를 보겠습니다.



Texture.vs


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
////////////////////////////////////////////////////////////////////////////////
// Filename: texture.vs
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// 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 TextureVertexShader(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;
    
    return output;
}
cs


이제 더이상 정점에 색상을 사용하지 않고 텍스쳐 좌표를 사용하게 될 것입니다. 텍스쳐에서는 U와 V좌표만을 사용하기 때문에 이를 표현하기 위해 float2 자료형을 이용합니다. 정점 셰이더와 픽셀 셰이더에서 텍스쳐 좌표를 나타내기 위해 TEXCOORD0이라는 것을 사용합니다. 여러 개의 텍스쳐 좌표가 가능하다면 그 값을 0부터 아무 숫자로나 지정할 수도 있습니다.


이전 튜토리얼의 컬러 버텍스 쉐이더와 비교하여 텍스처 버텍스 쉐이더의 유일한 차이점은 입력 버텍스에서 색상의 복사본을 얻는 대신 텍스처 좌표의 복사본을 가져 와서 픽셀 쉐이더로 전달한다는 것입니다.




Texture.ps


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
////////////////////////////////////////////////////////////////////////////////
// Filename: texture.ps
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture;
SamplerState SampleType;
 
 
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 TexturePixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
 
 
    // 이 텍스처 좌표 위치에서 샘플러를 사용하여 텍스처에서 픽셀 색상을 샘플링합니다.
    textureColor = shaderTexture.Sample(SampleType, input.tex);
 
    return textureColor;
}
 
cs


텍스쳐 픽셀 셰이더에는 두 개의 전역변수가 있습니다. 첫번째는 텍스쳐 그 자체인 Texture2D shaderTexture 입니다. 이것은 텍스쳐 자원으로서 모델에 텍스쳐를 그릴 때 사용될 것입니다. 두번째 새 변수는 SamplerState SampleType입니다. 샘플러 상태(Sampler state)는 도형에 셰이딩이 이루어질 때 어떻게 텍스쳐의 픽셀이 씌여지는 지를 수정할 수 있게 해 줍니다. 일례로 너무 멀리 있어 겨우 8픽셀만큼의 영역을 차지하는 도형의 경우 이 샘플러 상태를 사용하여 원래 텍스쳐의 어떤 픽셀 혹은 어떤 픽셀 조합을 사용해야 할지 결정합니다. 그 원본 텍스쳐는 256x256 픽셀의 크기일 수도 있으므로 매우 작아보이는 도형의 품질과 관련하여 이 결정은 매우 중요합니다. 이 샘플러 상태를 TextureShaderClass 클래스에 만들고 연결하여 픽셀 셰이더에서 이를 이용할 수 있게 할 것입니다.


픽셀 셰이더가 HLSL의 샘플링 함수를 사용하도록 수정되었습니다. 샘플링 함수(sample function)은 위에서 정의한 샘플러 상태와 텍스쳐 좌표를 사용합니다. 도형의 표면 UV좌표 위치에 들어갈 픽셀 값을 결정하고 반환하기 위해 이 두 변수를 사용합니다.




다음은 TextureShaderClass에 대해 알아보겠습니다. TextureShaderClass는 이전 듀토리얼 ColorShaderClass의 업데이트 된 버전입니다. 이 클래스는 정점 및 픽셀 쉐이더를 사용하여 3D 모델을 그리는 데 사용됩니다.



TextureShaderClass.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
#pragma once
 
class TextureShaderClass : public AlignedAllocationPolicy<16>
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
public:
    TextureShaderClass();
    TextureShaderClass(const TextureShaderClass&);
    ~TextureShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool Render(ID3D11DeviceContext*int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*);
 
private:
    bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
    void ShutdownShader();
    void OutputShaderErrorMessage(ID3D10Blob*, HWND, 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_sampleState = nullptr;
};
cs




TextureShaderClass.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
#include "stdafx.h"
#include "Textureshaderclass.h"
 
 
TextureShaderClass::TextureShaderClass()
{
}
 
 
TextureShaderClass::TextureShaderClass(const TextureShaderClass& other)
{
}
 
 
TextureShaderClass::~TextureShaderClass()
{
}
 
 
bool TextureShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더를 초기화합니다.
    return InitializeShader(device, hwnd, L"../Dx11Demo_05/texture.vs", L"../Dx11Demo_05/texture.ps");
}
 
 
void TextureShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련된 객체를 종료합니다.
    ShutdownShader();
}
 
 
bool TextureShaderClass::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 TextureShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    result = D3DCompileFromFile(vsFilename, NULLNULL"TextureVertexShader""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"TexturePixelShader""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_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_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_sampleState);
    if (FAILED(result))
    {
        return false;
    }
 
    return true;
}
 
 
void TextureShaderClass::ShutdownShader()
{
    // 샘플러 상태를 해제한다.
    if (m_sampleState)
    {
        m_sampleState->Release();
        m_sampleState = 0;
    }
 
    // 행렬 상수 버퍼를 해제합니다.
    if (m_matrixBuffer)
    {
        m_matrixBuffer->Release();
        m_matrixBuffer = 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 TextureShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
    // 에러 메시지를 출력창에 표시합니다.
    OutputDebugStringA(reinterpret_cast<const char*>(errorMessage->GetBufferPointer()));
 
    // 에러 메세지를 반환합니다.
    errorMessage->Release();
    errorMessage = 0;
 
    // 컴파일 에러가 있음을 팝업 메세지로 알려줍니다.
    MessageBox(hwnd, L"Error compiling shader.", shaderFilename, MB_OK);
}
 
 
bool TextureShaderClass::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 TextureShaderClass::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



다음은 TextureClass 입니다. TextureClass는 텍스쳐 자원을 불러오고, 해제하고, 접근하는 작업을 캡슐화합니다. 모든 텍스쳐에 대해 각각 이 클래스가 만들어져 있어야 합니다.


TextureClass .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
#pragma once
 
class TextureClass
{
private:
    struct TargaHeader
    {
        unsigned char data1[12];
        unsigned short width;
        unsigned short height;
        unsigned char bpp;
        unsigned char data2;
    };
 
public:
    TextureClass();
    TextureClass(const TextureClass&);
    ~TextureClass();
 
    bool Initialize(ID3D11Device*, ID3D11DeviceContext*char*);
    void Shutdown();
 
    ID3D11ShaderResourceView* GetTexture();
 
private:
    bool LoadTarga(char*int&int&);
 
private:
    unsigned char* m_targaData = nullptr;
    ID3D11Texture2D* m_texture = nullptr;
    ID3D11ShaderResourceView* m_textureView = nullptr;
};
cs




TextureClass .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
#include "stdafx.h"
#include "TextureClass.h"
 
 
TextureClass::TextureClass()
{
}
 
 
TextureClass::TextureClass(const TextureClass& other)
{
}
 
 
TextureClass::~TextureClass()
{
}
 
 
bool TextureClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
{
    int width = 0;
    int height = 0;
    
    // targa 이미지 데이터를 메모리에 로드합니다.
    if (!LoadTarga(filename, height, width))
    {
        return false;
    }
 
    //텍스처의 구조체를 설정합니다.
    D3D11_TEXTURE2D_DESC textureDesc;
    textureDesc.Height = height;
    textureDesc.Width = width;
    textureDesc.MipLevels = 0;
    textureDesc.ArraySize = 1;
    textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    textureDesc.SampleDesc.Count = 1;
    textureDesc.SampleDesc.Quality = 0;
    textureDesc.Usage = D3D11_USAGE_DEFAULT;
    textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
    textureDesc.CPUAccessFlags = 0;
    textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
 
    // 빈 텍스처를 생성합니다.
    HRESULT hResult = device->CreateTexture2D(&textureDesc, NULL&m_texture);
    if (FAILED(hResult))
    {
        return false;
    }
 
    //  targa 이미지 데이터의 너비 사이즈를 설정합니다.
    UINT rowPitch = (width * 4* sizeof(unsigned char);
 
    // targa 이미지 데이터를 텍스처에 복사합니다.
    deviceContext->UpdateSubresource(m_texture, 0NULL, m_targaData, rowPitch, 0);
 
    // 셰이더 리소스 뷰 구조체를 설정합니다.
    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    srvDesc.Format = textureDesc.Format;
    srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    srvDesc.Texture2D.MostDetailedMip = 0;
    srvDesc.Texture2D.MipLevels = -1;
 
    // 텍스처의 셰이더 리소스 뷰를 만듭니다.
    hResult = device->CreateShaderResourceView(m_texture, &srvDesc, &m_textureView);
    if (FAILED(hResult))
    {
        return false;
    }
 
    // 이 텍스처에 대해 밉맵을 생성합니다.
    deviceContext->GenerateMips(m_textureView);
 
    // 이미지 데이터가 텍스처에 로드 되었으므로 targa 이미지 데이터를 해제합니다.
    delete[] m_targaData;
    m_targaData = 0;
 
    return true;
}
 
 
void TextureClass::Shutdown()
{
    //텍스처 뷰 리소스를 해제한다.
    if (m_textureView)
    {
        m_textureView->Release();
        m_textureView = 0;
    }
 
    // 텍스쳐를 해제합니다.
    if (m_texture)
    {
        m_texture->Release();
        m_texture = 0;
    }
 
    // targa 이미지 데이터를 해제합니다.
    if (m_targaData)
    {
        delete[] m_targaData;
        m_targaData = 0;
    }
}
 
 
ID3D11ShaderResourceView* TextureClass::GetTexture()
{
    return m_textureView;
}
 
 
bool TextureClass::LoadTarga(char* filename, int& height, int& width)
{
    // targa 파일을 바이너리 모드로 파일을 엽니다.
    FILE* filePtr;
    if (fopen_s(&filePtr, filename, "rb"!= 0)
    {
        return false;
    }
 
    // 파일 헤더를 읽어옵니다.
    TargaHeader targaFileHeader;
    unsigned int count = (unsigned int)fread(&targaFileHeader, sizeof(TargaHeader), 1, filePtr);
    if (count != 1)
    {
        return false;
    }
 
    // 파일헤더에서 중요 정보를 얻어옵니다.
    height = (int)targaFileHeader.height;
    width = (int)targaFileHeader.width;
    int bpp = (int)targaFileHeader.bpp;
 
    // 파일이 32bit 인지 24bit인지 체크합니다.
    if (bpp != 32)
    {
        return false;
    }
 
    // 32 비트 이미지 데이터의 크기를 계산합니다.
    int imageSize = width * height * 4;
 
    //  targa 이미지 데이터 용 메모리를 할당합니다.
    unsigned char* targaImage = new unsigned char[imageSize];
    if (!targaImage)
    {
        return false;
    }
 
    // targa 이미지 데이터를 읽습니다.
    count = (unsigned int)fread(targaImage, 1, imageSize, filePtr);
    if (count != imageSize)
    {
        return false;
    }
 
    // 파일을 닫습니다.
    if (fclose(filePtr) != 0)
    {
        return false;
    }
 
    // targa 대상 데이터에 대한 메모리를 할당합니다.
    m_targaData = new unsigned char[imageSize];
    if (!m_targaData)
    {
        return false;
    }
 
    // targa 대상 데이터 배열에 인덱스를 초기화합니다.
    int index = 0;
 
    // targa 이미지 데이터에 인덱스를 초기화합니다.
    int k = (width * height * 4- (width * 4);
 
    // 이제 targa 형식이 거꾸로 저장되었으므로 올바른 순서로 targa 이미지 데이터를 targa 대상 배열에 복사합니다.
    for (int j = 0; j<height; j++)
    {
        for (int i = 0; i<width; i++)
        {
            m_targaData[index + 0= targaImage[k + 2];  // 빨강
            m_targaData[index + 1= targaImage[k + 1];  // 녹색
            m_targaData[index + 2= targaImage[k + 0];  // 파랑
            m_targaData[index + 3= targaImage[k + 3];  // 알파
 
                                                         // 인덱스를 targa 데이터로 증가시킵니다.
            k += 4;
            index += 4;
        }
 
        // targa 이미지 데이터 인덱스를 역순으로 읽은 후 열의 시작 부분에서 이전 행으로 다시 설정합니다.
        k -= (width * 8);
    }
 
    // 대상 배열에 복사 된 targa 이미지 데이터를 해제합니다.
    delete[] targaImage;
    targaImage = 0;
 
    return true;
}
cs





ModelClass는 지난 튜토리얼의 내용에 더해 텍스쳐를 지원하는 내용이 추가되었습니다.



ModelClass.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
#pragma once
 
class TextureClass;
 
class ModelClass : public AlignedAllocationPolicy<16>
{
private:
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
    };
 
public:
    ModelClass();
    ModelClass(const ModelClass&);
    ~ModelClass();
 
    bool Initialize(ID3D11Device*, ID3D11DeviceContext*char*);
    void Shutdown();
    void Render(ID3D11DeviceContext*);
 
    int GetIndexCount();
    ID3D11ShaderResourceView* GetTexture();
 
private:
    bool InitializeBuffers(ID3D11Device*);
    void ShutdownBuffers();
    void RenderBuffers(ID3D11DeviceContext*);
 
    bool LoadTexture(ID3D11Device*, ID3D11DeviceContext*char*);
    void ReleaseTexture();
 
private:
    ID3D11Buffer* m_vertexBuffer = nullptr;
    ID3D11Buffer* m_indexBuffer = nullptr;
    int m_vertexCount = 0;
    int m_indexCount = 0;
    TextureClass* m_Texture = nullptr;
};
cs



ModelClass.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
#include "stdafx.h"
#include "TextureClass.h"
#include "modelclass.h"
 
 
ModelClass::ModelClass()
{
}
 
 
ModelClass::ModelClass(const ModelClass& other)
{
}
 
 
ModelClass::~ModelClass()
{
}
 
 
bool ModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* textureFilename)
{
    // 정점 및 인덱스 버퍼를 초기화합니다.
    if (!InitializeBuffers(device))
    {
        return false;
    }
 
    // 이 모델의 텍스처를 로드합니다.
    return LoadTexture(device, deviceContext, textureFilename);
}
 
 
void ModelClass::Shutdown()
{
    // 모델 텍스쳐를 반환합니다.
    ReleaseTexture();
 
    // 버텍스 및 인덱스 버퍼를 종료합니다.
    ShutdownBuffers();
}
 
 
void ModelClass::Render(ID3D11DeviceContext* deviceContext)
{
    // 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓습니다.
    RenderBuffers(deviceContext);
}
 
 
int ModelClass::GetIndexCount()
{
    return m_indexCount;
}
 
 
ID3D11ShaderResourceView* ModelClass::GetTexture()
{
    return m_Texture->GetTexture();
}
 
 
bool ModelClass::InitializeBuffers(ID3D11Device* device)
{
    // 정점 배열의 정점 수를 설정합니다.
    m_vertexCount = 3;
 
    // 인덱스 배열의 인덱스 수를 설정합니다.
    m_indexCount = 3;
 
    // 정점 배열을 만듭니다.
    VertexType* vertices = new VertexType[m_vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 인덱스 배열을 만듭니다.
    unsigned long* indices = new unsigned long[m_indexCount];
    if (!indices)
    {
        return false;
    }
 
    // 정점 배열에 값을 설정합니다.
    vertices[0].position = XMFLOAT3(-1.0f, -1.0f, 0.0f);  // Bottom left.
    vertices[0].texture = XMFLOAT2(0.0f, 1.0f);
 
    vertices[1].position = XMFLOAT3(0.0f, 1.0f, 0.0f);  // Top middle.
    vertices[1].texture = XMFLOAT2(0.5f, 0.0f);
 
    vertices[2].position = XMFLOAT3(1.0f, -1.0f, 0.0f);  // Bottom right.
    vertices[2].texture = XMFLOAT2(1.0f, 1.0f);
 
    // 인덱스 배열에 값을 설정합니다.
    indices[0= 0;  // Bottom left.
    indices[1= 1;  // Top middle.
    indices[2= 2;  // Bottom right.
 
    // 정적 정점 버퍼의 구조체를 설정합니다.
    D3D11_BUFFER_DESC vertexBufferDesc;
    vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = 0;
    vertexBufferDesc.MiscFlags = 0;
    vertexBufferDesc.StructureByteStride = 0;
 
    // subresource 구조에 정점 데이터에 대한 포인터를 제공합니다.
    D3D11_SUBRESOURCE_DATA vertexData;
    vertexData.pSysMem = vertices;
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;
 
    // 이제 정점 버퍼를 만듭니다.
    if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer)))
    {
        return false;
    }
 
    // 정적 인덱스 버퍼의 구조체를 설정합니다.
    D3D11_BUFFER_DESC indexBufferDesc;
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(unsigned long* m_indexCount;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;
    indexBufferDesc.StructureByteStride = 0;
 
    // 인덱스 데이터를 가리키는 보조 리소스 구조체를 작성합니다.
    D3D11_SUBRESOURCE_DATA indexData;
    indexData.pSysMem = indices;
    indexData.SysMemPitch = 0;
    indexData.SysMemSlicePitch = 0;
 
    // 인덱스 버퍼를 생성합니다.
    if (FAILED(device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer)))
    {
        return false;
    }
 
    // 생성되고 값이 할당된 정점 버퍼와 인덱스 버퍼를 해제합니다.
    delete[] vertices;
    vertices = 0;
 
    delete[] indices;
    indices = 0;
 
    return true;
}
 
 
void ModelClass::ShutdownBuffers()
{
    // 인덱스 버퍼를 해제합니다.
    if (m_indexBuffer)
    {
        m_indexBuffer->Release();
        m_indexBuffer = 0;
    }
 
    // 정점 버퍼를 해제합니다.
    if (m_vertexBuffer)
    {
        m_vertexBuffer->Release();
        m_vertexBuffer = 0;
    }
}
 
 
void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
    // 정점 버퍼의 단위와 오프셋을 설정합니다.
    UINT stride = sizeof(VertexType);
    UINT offset = 0;
 
    // 렌더링 할 수 있도록 입력 어셈블러에서 정점 버퍼를 활성으로 설정합니다.
    deviceContext->IASetVertexBuffers(01&m_vertexBuffer, &stride, &offset);
 
    // 렌더링 할 수 있도록 입력 어셈블러에서 인덱스 버퍼를 활성으로 설정합니다.
    deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
 
    // 정점 버퍼로 그릴 기본형을 설정합니다. 여기서는 삼각형으로 설정합니다.
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
 
 
bool ModelClass::LoadTexture(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* filename)
{
    // 텍스처 오브젝트를 생성한다.
    m_Texture = new TextureClass;
    if (!m_Texture)
    {
        return false;
    }
 
    // 텍스처 오브젝트를 초기화한다.
    return m_Texture->Initialize(device, deviceContext, filename);
}
 
 
void ModelClass::ReleaseTexture()
{
    // 텍스처 오브젝트를 릴리즈한다.
    if (m_Texture)
    {
        m_Texture->Shutdown();
        delete m_Texture;
        m_Texture = 0;
    }
}
cs





다음은 GraphicsClass 입니다. GraphicsClass 클래스는 ColorShaderClass의 멤버변수를 TextureShaderClass 멤버변수 사용으로 변경되었습니다.



GraphicsClass.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
 
/////////////
// GLOBALS //
/////////////
const bool FULL_SCREEN = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
 
 
class D3DClass;
class CameraClass;
class ModelClass;
class TextureShaderClass;
 
class GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass&);
    ~GraphicsClass();
 
    bool Initialize(intint, HWND);
    void Shutdown();
    bool Frame();
 
private:
    bool Render();
 
private:
    D3DClass* m_Direct3D = nullptr;
    CameraClass* m_Camera = nullptr;
    ModelClass* m_Model = nullptr;
    TextureShaderClass* m_TextureShader = nullptr;
};
cs



GraphicsClass.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
#include "stdafx.h"
#include "d3dclass.h"
#include "cameraclass.h"
#include "modelclass.h"
#include "textureshaderclass.h"
#include "graphicsclass.h"
 
 
GraphicsClass::GraphicsClass()
{
}
 
 
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
 
 
GraphicsClass::~GraphicsClass()
{
}
 
 
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
    // Direct3D 객체 생성
    m_Direct3D = new D3DClass;
    if(!m_Direct3D)
    {
        return false;
    }
 
    // Direct3D 객체 초기화
    if(!m_Direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN,
                                SCREEN_DEPTH, SCREEN_NEAR))
    {
        MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
        return false;
    }
 
    // m_Camera 객체 생성
    m_Camera = new CameraClass;
    if (!m_Camera)
    {
        return false;
    }
 
    // 카메라 포지션 설정
    m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
 
    // m_Model 객체 생성
    m_Model = new ModelClass;
    if (!m_Model)
    {
        return false;
    }
 
    // m_Model 객체 초기화
    if (!m_Model->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), 
                            "../Dx11Demo_05/data/stone01.tga"))
    {
        MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
        return false;
    }
 
    // m_TextureShader 객체 생성
    m_TextureShader = new TextureShaderClass;
    if (!m_TextureShader)
    {
        return false;
    }
 
    // m_TextureShader 객체 초기화
    if (!m_TextureShader->Initialize(m_Direct3D->GetDevice(), hwnd))
    {
        MessageBox(hwnd, L"Could not initialize the color shader object.", L"Error", MB_OK);
        return false;
    }
 
    return true;
}
 
 
void GraphicsClass::Shutdown()
{
    // m_TextureShader 객체 반환
    if (m_TextureShader)
    {
        m_TextureShader->Shutdown();
        delete m_TextureShader;
        m_TextureShader = 0;
    }
 
    // m_Model 객체 반환
    if (m_Model)
    {
        m_Model->Shutdown();
        delete m_Model;
        m_Model = 0;
    }
 
    // m_Camera 객체 반환
    if (m_Camera)
    {
        delete m_Camera;
        m_Camera = 0;
    }
 
    // Direct3D 객체 반환
    if (m_Direct3D)
    {
        m_Direct3D->Shutdown();
        delete m_Direct3D;
        m_Direct3D = 0;
    }
}
 
 
bool GraphicsClass::Frame()
{
    // 그래픽 랜더링 처리
    return Render();
}
 
 
bool GraphicsClass::Render()
{
    // 씬을 그리기 위해 버퍼를 지웁니다
    m_Direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져옵니다
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
    m_Direct3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_Direct3D->GetProjectionMatrix(projectionMatrix);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비합니다.
    m_Model->Render(m_Direct3D->GetDeviceContext());
 
    // 텍스쳐 쉐이더를 사용하여 모델을 렌더링합니다.
    if (!m_TextureShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix,
                                viewMatrix, projectionMatrix, m_Model->GetTexture()))
    {
        return false;
    }
 
    // 버퍼의 내용을 화면에 출력합니다
    m_Direct3D->EndScene();
 
    return true;
}
cs




출력 화면




마치면서


여기까지 잘 따라오셨다면 이제 여러분은 텍스쳐를 불러오고, 도형에 입히고, 셰이더를 이용하여 그리는 방법의 기본을 아시게 되었습니다



연습문제


1. 코드를 다시 컴파일하고 실제로 화면에 텍스쳐가 입혀진 삼각형이 나오는지 확인해 보십시오. Esc키를 눌러 나오십시오.


2. 여러분만의 dds 텍스쳐를 만들고 seafloor.dds 파일이 있는 폴더에 저장하십시오. GraphicsClass::Initialize 함수에서 모델 초기화를 여러분의 텍스쳐로 하도록 바꾸고 다시 컴파일하여 실행해 보십시오.


3. 코드를 수정하여 두 개의 삼각형이 사각형을 이루도록 바꾸어 보십시오. 사각형에 전체 텍스쳐를 입혀서 화면에 텍스쳐의 모든 부분이 제대로 보이도록 해 보십시오.


4. MIN_MAG_MIP_LINEAR 필터의 효과를 보기 위해 다른 거리가 되도록 카메라를 이동시켜 보십시오.


5. 다른 필터를 시도해 보고 카메라를 옮겨 다른 결과가 나오는지 확인해 보십시오.



소스코드


소스코드 : Dx11Demo_05.zip